Vue SPA 项目,前端工程构建打包后使用 node 服务器,前端页面路由跳转后刷新页面出现 404 或者访问错误的情况
解决方案:
修改前端路由模式
store/index.js
import Vue from 'vue'
import Router from 'vue-router'
const home = () => import('../views/home.vue')
Vue.use(Router)
export default new Router({
mode: 'history',
base: '/xxx',
routes: [
{
path: '*',
component: notFound
},
{
path: '/',
name: 'home',
component: home
}
...
Vue Router 官网说明
https://router.vuejs.org/guide/essentials/history-mode.html#example-server-configurations
Node 服务端添加 connect-history-api-fallback 中间件
node server.js
var express = require('express');
var history = require('connect-history-api-fallback');
var app = express();
var path = require('path');
app.use(express.static('dist'));
app.use(history({ verbose: true, index: '/' }));
app.get('/', (req, res) => {
res.sendFile(path.resolve('./dist/xxx/index.html'));
});
// server
var server = app.listen('3002', (req, res) => {
var host = server.address().address;
var port = server.address().port;
console.log('server is running . http://%s:%s', host, port);
});
connect-history-api-fallback
https://github.com/bripkens/connect-history-api-fallback