代理服务器中间件 npm install --save-dev http-proxy-middleware
解决跨域npm install cors
const express = require('express');
const proxy = require('http-proxy-middleware').createProxyMiddleware;
const app = express();
const cors = require('cors');
app.use(cors())
app.get('/', function (req, res) {
res.send('Hello World');
})
const proxyPath = '***************'
const proxyOption = {
target: proxyPath,
changeOrigin: true,
ws: true,
pathRewrite: {
'^/api/': ''
},
// 需要监听是否正常发送请求以及接收到响应信息可添加
onProxyReq: function (proxyReq, req, res) {
proxyReq.setHeader('Cache-Control', 'no-cache');
/**头部*/
console.log('headers', req.headers);
/**请求方法*/
console.log('method', req.method);
/**请求URL*/
console.log('url', req.path);
/**get请求方法参数*/
console.log('query', req.query);
/**post请求方法参数*/
var raw = '';
req.on('data', function (chunk) {
raw += chunk;
});
req.on('end', function () {
console.log('raw', raw);
});
},
onProxyRes: function (proxyRes, req, res) {
/**获取接口返回的数据*/
let body = ''
proxyRes.on('data', function (chunk) {
body += chunk;
})
proxyRes.on('end', function () {
console.log('body', body);
})
},
onError: function (err, req, res) {
console.log(err)
console.log(req)
console.log(res)
}
}
app.use('/api', proxy(proxyOption))
const server = app.listen(3000, function () {
const host = server.address().address
const port = server.address().port
console.log("应用实例,访问地址为 http://%s:%s", host, port)
})