一、首先createWebHistory 和createWebHashHistory 的区别
- 主要是在浏览器地址栏上的显示的区别:分别类似 XXX.com/user/id 和XXX.com/#/user/id 很显然前者看起来更加好看一点,后者多了个#号,所以很多宝宝们都不喜欢,网易云音乐就是用的前者
- 实际上输入地址回车的瞬间都会发起一个请求就是请求我们打包目录下面的index.html,唯一不同的是createWebHistory请求的XXX.com/user/id 是一个路径,这个目录理论上是不存在的,但是浏览器默认在回车的时候发起请求,所以为了能请求到文件,就需要服务器端的配合(这个下面再说),而createWebHashHistory请求的就是XXX.com/ 默认会请求到 XXX.com/index.html 或 XXX.com/index.htm ..这个就不需要服务器的额外配合了
- 由于是前后端分离,路由这一块的逻辑 毋庸置疑都是由前端处理了
二、createWebHashHistory 这个后端如何帮我们处理
- 使用nginx 路径如果匹配不到直接返回 index.html (注意是直接返回不是不是302重定向哦)
http {
# ...
server {
# ...
location / {
root html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
}
}
- 使用node服务转发 也是可以的
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')
})
-
静态资源找不到的问题
情况一: vue.config.js 打包的路径不对
module.exports = {
//...
publicPath: "/", //这个地方不要用'./'
outputDir: "dist",
}
其他情况及解决评论区见