前后端分离项目,接口跨域用nodejs代理

  nodejs, 前端
403 views

javascript
var express = require(‘express’);
const {createProxyMiddleware} = require(‘http-proxy-middleware’);
const app = express();
//设置监听的端口
app.set(‘port’, ‘8099’);

app.all(‘‘, function (req, res, next) { // 解决跨域问题
res.header(“Access-Control-Allow-Origin”, “
“);
res.header(“Access-Control-Allow-Headers”, “token,Content-Type,Content-Length, Authorization, Accept,X-Requested-With”);
res.header(“Access-Control-Allow-Methods”, “PUT,POST,GET,DELETE,OPTIONS”);
if (req.method == “OPTIONS”) {
res.send(200);
} else {
next();
}
});

var options = {
//设置目标网址
target: ‘http://baidu.com/’,
changeOrigin: true,
};
var exampleProxy = createProxyMiddleware(options);
app.use(‘/’, exampleProxy);
app.listen(app.get(‘port’), () => {
console.log(server running @${app.get('port')});
});

// 1.首先安装依赖 cnpm i express http-proxy-middleware –save-dev
// 2.然后运行脚本 node test.js
// 3.这时候在浏览器访问http://127.0.0.1:8099 就相当于访问http://baidu.com/
“`

LEAVE A COMMENT