一、node配置
在index.js同级目录创建public文件夹,将打包好的dist文件放入public中
const express = require("express");
const app = express();
app.use(express.static(__dirname + "/public"));
app.listen(8081, () => {
console.log("http://localhost:8081");
});
二、解决history路由跳转后,刷新浏览器,页面报404的问题
原因分析:浏览器将请求的路由都看成请求来处理了,而后台不存在该请求
方法一 :将路由模式由history改为hash
const router = new VueRouter({
mode: 'hash', // history改为hash
base: process.env.BASE_URL,
routes
})
方法二:在server.js中将所有的请求匹配都返回index.html
// 将所有的请求匹配都返回index.html,将接口处理转交给js处理
app.get("*", (req, res) => {
res.sendFile(__dirname, "/public/index.html");
});
方法三:使用第三方的插件connect-history-api-fallback
1.安装插件
npm i connect-history-api-fallback
2.引入插件
const history = require("connect-history-api-fallback");
3.配置使用
// 必须放到配置静态资源之前
app.use(history());
// 配置静态资源
app.use(express.static(__dirname + "/public"));
三、解决跨域问题
1.安装插件
npm i http-proxy-middleware
2.引入http代理服务器插件
const { createProxyMiddleware } = require("http-proxy-middleware");
3.配置代理服务器
app.use(
"/api",
createProxyMiddleware({
target: "http://www.example.org/secret",
changeOrigin: true,
pathRewrite: { "^/api": "" },
})
);