如果在express项目中同时使用了 express.json() 和 http-proxy-middleware 这两个中间件,那么带有payload的post请求就会报504 gateway timeout的error。
解决办法:
在 option onProxyReq 中加入对payload的处理
onProxyReq = (proxyReq, req: Request, res) => {
if (!req.body || !Object.keys(req.body).length) {
return;
}
const contentType = proxyReq.getHeader('Content-Type');
const writeBody = (bodyData: string) => {
proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
proxyReq.write(bodyData);
};
if (contentType.toString().includes('application/json')) {
writeBody(JSON.stringify(req.body));
}
if (contentType.toString().includes('application/x-www-form-urlencoded')) {
writeBody(querystring.stringify(req.body));
}
}