const express = require("express");
const { createProxyMiddleware } = require("http-proxy-middleware");
const app = express();
// 设置允许跨域响应头
app.all("*", function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type");
res.header("Access-Control-Allow-Methods", "*");
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
// http-proxy-middleware中间件
app.use(
"/",
createProxyMiddleware({
target: "http://localhost:3000",
changeOrigin: true
})
);
app.listen(8080);
服务器3000端口,前端请求的是8080端口,产生了跨域行为u。使用中间件代理跨域服务器监听前端请求转发到服务器拿到结果随后把结果发送回客户端。