vue路由history模式下打包的dist如何配置node访问
之前写过一篇【打包出的dist包怎么在本地用node访问运行】(https://www.cnblogs.com/grow-up-up/p/16672764.html),但今天有个项目,打包出dist后,按照之前写的进行配置后,发现访问不了,只能访问path为“/”,然后重定向后的那个页面,其他的输入path进行访问都都是404不能找到。后来发现一个问题,那就是我这个访问失败的项目,它的路由模式是history,后经过百度,只需要再安装一下【
connect-history-api-fallback】这个依赖引用一下即可(下面代码标红的就是补充的)。
index.js :
1 import express from 'express'; 2 import path from 'path'; 3 import os from 'os'; 4 import proxy from 'http-proxy-middleware'; 5 import connectHistoryApiFallback from 'connect-history-api-fallback'; 6 const getIPAddress = () => { 7 const interfaces = os.networkInterfaces(); 8 for (const devName in interfaces) { 9 const iFace = interfaces[devName]; 10 for (let i = 0; i < iFace.length; i++) { 11 const alias = iFace[i]; 12 if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) { 13 return alias.address; 14 } 15 } 16 } 17 }; 18 const app = express(); 19 20 // 额外需要补充的 21 app.use('/', connectHistoryApiFallback()); // 通过js控制路由 22 23 app.use('/', express.static(path.resolve(process.cwd(), './dist'))); 24 app.get('/', async (req, res) => { 25 res.sendFile(path.resolve(process.cwd(), './dist/index.html')); 26 }); 27 app.use( 28 '^/admin/', 29 proxy.createProxyMiddleware({ 30 target: 'https://xxxxx', // 服务器api地址目录 31 changeOrigin: true, 32 pathRewrite: {}, 33 }) 34 ); 35 app.use( 36 '^/gov-outside/', 37 proxy.createProxyMiddleware({ 38 target: 'https://yyyyy', // 服务器api地址目录 39 changeOrigin: true, 40 pathRewrite: {}, 41 }) 42 ); 43 app.listen(9528, () => { 44 console.log( 45 ` Your service run on:\n`, 46 `http://localhost:${9528}\n`, 47 `http://${getIPAddress()}:${9528}\n` 48 ); 49 });