node中使用proxy解决前端跨域

晴朗的天空来之不易
2021-4-12 / 0 评论 / 809 阅读 / 正在检测是否收录...

# 本地开发dev起代理服务解决跨域问题

npm i http-proxy-middleware --save
var express = require('express');
var { createProxyMiddleware } = require('http-proxy-middleware');
var app = express();

app.use('/',createProxyMiddleware(
    { target: 'http://www.baidu.com', changeOrigin: true }
));
app.listen(9000);

# node-express路由设置跨域访问

//设置跨域访问
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')
    next();
});
0