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>
nginx
location / {
try_files $uri $uri/ /index.html;
}
本机 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)
})