我是标题
代理转发除了 Nginx,大家(前端)可能接触比较多的是 webpack 中的 devServer(webpack-dev-server)。
若你 webpack 的 proxy 使用较多的话,那?那别看了~。
快速开箱。所有路径都会转发至 localhost:8001,changeOrigin 为 true 时,会将请求头中的 host 更改为 target url。
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
修改请求体,可使用 body-parser 中间件,做到快速修改。
由于更改 body 后,Content-Length 长度并未更新,会导致请求方读取失败。若未更改仍需配置,因为 bodyParser 中或者其他未指定路径中使用 req.on('data') 操作都会影响 http-proxy-middleware。
解决方案:更换 bodyParser 的位置,或使用路径来区分,或使用 fixRequestBody
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);
修改返回
使用 responseInterceptor 方法可获取处理好的返回体,return 即可。
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
}),
},
});
























