vue-router history模式
vue-router
的history
模式需要将路由配置中的mode
设置成history
,同时还需要在服务器端进行相应的配置。
与hash
模式相比,在history
模式下,页面的url
中会少一些如#
这样的符号:
hash:www.example.com/#/login
history:www.example.com/login
单页应用程序中,在history
模式下浏览器会向服务器请求这个页面,但是服务器端并不存在这个页面于是就返回404。所以这个时候就需要给服务器端进行配置:除了静态资源以外都需要返回单页应用的index.html
。
服务器配置——nodejs
在nodejs
服务器中需要引入connect-history-api-fallback
这个模块来处理history
模式,并在使用处理静态资源的中间件前使用这个模块:
const path = require('path')
// 导入处理history模式的模块
const history = require('connect-history-api-fallback')
const express = require('express')
const app = express()
// 注册处理history模式的中间件
app.use(history())
// 处理静态资源的中间件
app.use(express.static(path.join(__dirname, './web')))
app.listen(3000, () => {
console.log('service started at port 3000')
})
服务器配置——nginx
先将打包后的文件放入html
文件夹下,再打开conf
文件夹下nginx.conf
文件,修改如下配置:
http {
# ...other config
server {
# ...other config
location / {
root html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
}
}