apache 中的 vue.js 路由问题

LJP*_*LJP 2 apache vue-router

我有一个带有 vue 路由器的 vue.js 应用程序来渲染各种组件。我有一个/home加载 home 组件的路径。在开发环境中,我可以通过localhost:8080/home在地址栏中给出并使用<router-link>. 当我将生产版本部署到 apache 服务器时,当我给出localhost/home错误时

在此服务器上找不到请求的 URL /home。

但是localhost/home当我们点击链接时,这些链接是有效的并且显示在地址栏中 为什么会发生这种情况?如何解决这个问题?

Spe*_*sys 5

直接来自 Vue 路由器网站。

vue-router 的默认模式是哈希模式——它使用 URL 哈希来模拟完整的 URL,这样当 URL 更改时页面不会重新加载。

为了摆脱散列,我们可以使用路由器的历史模式,它利用 history.pushState API 实现无需重新加载页面的 URL 导航:

const router = new VueRouter({ mode: 'history', routes: [...] }) 使用历史模式时,URL 将看起来“正常”,例如 http://oursite.com/user/id。美丽的!

但是,这里出现了一个问题:由于我们的应用程序是单页客户端应用程序,没有适当的服务器配置,如果用户直接在浏览器中访问http://oursite.com/user/id,他们将收到 404 错误。现在这很丑陋。

不用担心:要解决这个问题,您需要做的就是向您的服务器添加一个简单的全能回退路由。如果 URL 不匹配任何静态资源,它应该提供与您的应用所在的 index.html 页面相同的页面。再次美丽!

阿帕奇

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>
Run Code Online (Sandbox Code Playgroud)

nginx

location / {
  try_files $uri $uri/ /index.html;
}
Run Code Online (Sandbox Code Playgroud)

原生 Node.js

const http = require('http')
const fs = require('fs')
const httpPort = 80

http.createServer((req, res) => {
  fs.readFile('index.htm', 'utf-8', (err, content) => {
    if (err) {
      console.log('We cannot open "index.htm" file.')
    }

    res.writeHead(200, {
      'Content-Type': 'text/html; charset=utf-8'
    })

    res.end(content)
  })
}).listen(httpPort, () => {
  console.log('Server listening on: http://localhost:%s', httpPort)
})
Run Code Online (Sandbox Code Playgroud)

[0] https://router.vuejs.org/en/essentials/history-mode.html