express
使用express来代理后端的请求,方便前端项目开发,尤其是前端跨的时候。(解决跨域,不要固化思维就一定要用nginx)。这也是很好的工具。
安装
初始化项目
npm init
安装相关的模块
npm install express
npm install http-proxy-middleware
代理后端请求
const express = require("express");
const { createProxyMiddleware } = require("http-proxy-middleware");
const app = express();
app.use(express.static("dist"));
// 静态文件
app.get("*", (req, res) => {
res.sendFile(__dirname + "/dist/index.html");
});
//代理后端请求
app.use(
"/api",
createProxyMiddleware({
target: "http://localhost:5000",
changeOrigin: true,
// 这里是 pathRewrite,跟 vite 不太一样
pathRewrite: (path) => path.replace(/^\/api/, ""),
})
);
app.listen(5000);