一、問題描述
我們把Vue
項目的路由模式,設置成history
然后,build
并把dist
中的代碼部署到node+express
服務中
訪問頁面后,刷新頁面報404
問題
二、原因分析
server.js
文件
會發現,文件中配置的路徑沒有Vue
項目中對應的路徑
所以,刷新頁面時,報404
這也是history
模式的一個小問題。
const express = require('express')
const app = express()
app.use(express.static(__dirname+'/static'))app.get('/students',(request,response)=>{const students = [{id:'001',name:'tom',age:18},{id:'002',name:'jerry',age:19},{id:'003',name:'tony',age:120},]response.send(students)
})app.listen(5000,(err)=>{if(!err) console.log('服務器1啟動成功了,請求學生信息地址為:http://localhost:5000/students');
})
三、解決
這個問題的本質,是請求路徑在后端沒對應上
所以,要解決這個問題,需要從后端代碼著手
我這里用的是node+express
部署項目
就這個情況,來解決
1、安裝connect-history-api-fallback
中間件
npm i connect-history-api-fallback
2、修改server.js
關鍵代碼:
const history = require('connect-history-api-fallback')
app.use(history())
完整配置:
const express = require('express')
const history = require('connect-history-api-fallback')const app = express()
app.use(history())
app.use(express.static(__dirname+'/static'))app.get('/students',(request,response)=>{const students = [{id:'001',name:'tom',age:18},{id:'002',name:'jerry',age:19},{id:'003',name:'tony',age:120},]response.send(students)
})app.listen(5000,(err)=>{if(!err) console.log('服務器1啟動成功了,請求學生信息地址為:http://localhost:5000/students');
})
重啟項目,即可。
此時,刷新頁面,不會報404
問題。