官方文档.
src/setupProxy.js源代码
const {
createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
//http://localhost:4568/ 这是服务器域名
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:4568/',
changeOrigin: true,
pathRewrite: {
'^/api': '',
},
})
);
};
请求代码demo
axios.get('http://localhost:3000/api/v1/device')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
服务器代码(只是搭建一个服务器测试我的前端服务器代理配置)
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("Hello world");
});
app.all("*", function (req, res, next) {
// res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", " 3.2.1");
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
app.listen(4568, (req, res) => {
console.log(res);
console.log("Server is running at http://localhost:4568");
});