当尝试使用 axios 将 POST 请求从 Express 后端转发到另一个后端时,我收到 axios 错误“CanceledError:请求流已中止”。 GET 请求不会发生这种情况。另一个后端是通过 NextJS。
import axios from 'axios';
import express from 'express';
import { parse } from 'url';
DESTINATION_URL = ...
async function forwardRequest(req: express.Request, res: express.Response) {
const { path } = parse(req.url, true);
const forwardUrl = DESTINATION_URL + path;
await axios(forwardUrl, {
method: req.method,
data: req,
responseType: 'stream',
}).then((response) => {
// Pipe data from destination response to res
response.data.pipe(res);
});
}
const ForwardRouter = express.Router();
ForwardRouter.all('*', forwardRequest);
export default ForwardRouter
我尝试更改 axios 请求以包含与函数参数请求相同的标头,但这导致所有请求(包括 GET)都失败,并出现不同的错误。 CORS 在另一个后端配置为 * 并允许使用 Access-Control-Allow-Origin。
问题来自于在 axios 请求中使用 data: req 而不是 data: req.body。