在 node 中快速代理请求(Proxy),解决跨域或请求转发问题 - http-proxy-middleware 修改请求体和返回
我是标题
原生 http
模块使用
const http = require('node:http');
const { createProxyMiddleware } = require('http-proxy-middleware');
const server = http.createServer(
createProxyMiddleware({
target: 'http://localhost:8001',
// 修改 request headers host 为 target
changeOrigin: true,
// http://localhost:8001/old/api/123 => http://localhost:8001/new/api/123
pathRewrite: { '^/old/api': '/new/api' },
// http://localhost:8001 any requset => http://localhost:8001/api
pathRewrite: (path, req) => {
return '/api';
},
}),
);
server.listen({ port: 8000 }, () => {
console.log('server run');
});
express 中使用
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const apiProxy = createProxyMiddleware({
target: 'http://localhost:8001',
changeOrigin: true,
});
const app = express();
app.use('/api', apiProxy);
// or
// app.use(apiProxy);
app.listen(8000);
更改请求头和请求体
配合 bodyParser
https://github.com/chimurai/http-proxy-middleware/issues/320#issuecomment-474922392 > https://github.com/chimurai/http-proxy-middleware/pull/725
const bodyParser = require('body-parser');
const apiProxy = createProxyMiddleware({
target: 'http://localhost:8001',
changeOrigin: true,
on: {
proxyReq: fixRequestBody,
proxyReq: (proxyReq, req, res, options) => {
// 修改请求头
proxyReq.setHeader('Authorization', 'xxx');
fixRequestBody(proxyReq, req);
},
},
});
const app = express();
app.use(bodyParser.json());
app.use((req, res, next) => {
req.body.xxx = 'xxx';
next();
});
app.use(apiProxy);
修改返回
const { createProxyMiddleware, responseInterceptor } = require('http-proxy-middleware');
const apiProxy = createProxyMiddleware({
target: 'http://localhost:8001',
changeOrigin: true,
selfHandleResponse: true,
on: {
proxyRes: (proxyRes, req, res) => {
proxyRes.headers['Access-Control-Allow-Origin'] = 'baidu.com';
proxyRes.headers['Vary'] = 'Origin';
responseInterceptor((responseBuffer, proxyRes, req, res) => {
const response = responseBuffer.toString('utf8');
return 'new respone here';
})(proxyRes, req, res);
},
// 不修改返回头
proxyRes: responseInterceptor(async (responseBuffer, proxyRes, req, res) => {
const response = responseBuffer.toString('utf8'); // convert buffer to string
return response.replace('Hello', 'Goodbye'); // manipulate response and return the result
}),
},
});
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 kshao-blog-前端知识记录!
评论