背景:
在history模式下的404空白 * 这种网上已经说了很多了,你在history模式下时,你会发现这种url方式你直接回车,它是会以http get方式请求后台,但是后台没有你这个请求路径,所以会报404,而这个路径是前台自己定义的,所以要由前台处理,因为vue单页面应用,所以它只有一个页面index.html,所以一旦后台或者nignx 404了,就让它重定向到index.html,这样前台获取了这个路径,它就会根据自己路由来处理了
文件夹目录结构
1.新建一个node_server文件夹
2.运行npm init 生成一个npm包项目
3.安装 npm i express connect-history-api-fallback
4.将vue脚手架的项目里dist目录下的文件夹里的内容复制进来
server.js
const express = require('express')
const history = require('connect-history-api-fallback')
// ngix也可以判断哪些是前端路由,哪些是后端路由
const app = express()
app.use(history())
// 启动静态资源目录
app.use(express.static(__dirname+'/static'))
// 服务器中间件 connect-history-api-fallback 专门解决history模式404问题,匹配到底哪些是前端路由,哪些是后端路由
app.get('/person',(req, res)=> {
res.send({
name: 'gc',
age: 19
})
})
app.listen(5005,(err)=> {
if(!err) console.log('服务器启动成功了额')
})
package.json
{
"name": "express-node",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"connect-history-api-fallback": "^2.0.0",
"express": "^4.18.2"
}
}
启动node server