vue-router history模式服务器端配置

2,147 阅读1分钟

vue-router history模式

vue-routerhistory模式需要将路由配置中的mode设置成history,同时还需要在服务器端进行相应的配置。

hash模式相比,在history模式下,页面的url中会少一些如#这样的符号:

hashwww.example.com/#/login

historywww.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;
        }
    }
}