gpt4 book ai didi

node.js - 代理在 NextJS(也是 NodeJS)中传递 multipart

转载 作者:行者123 更新时间:2023-12-01 23:09:55 29 4
gpt4 key购买 nike

我的任务是通过 NextJS api 路由代理传递 multipart/form-data,但内置的 bodyParser 会破坏传入的多部分数据。任何其他 NodeJS 插件不允许我代理传递清晰字节的多部分数据并使其他对象不是表单数据。

那么如何在没有插件的情况下代理传递 NextJS API 路由中的 multipart/form-data?

最佳答案

下一段代码是在没有NextJS插件的情况下成功代理传递multipart/form-data的解决方案:

// /pages/api/miltipart.ts

// helpers to generate cookies
import { setCookies } from '@utils/api';
import type { NextApiRequest, NextApiResponse } from 'next';

// turn off default parser for current route
export const config = {
api: {
bodyParser: false,
},
};

const handler = async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
// create container for all buffers of multipart/form-data
const buffers: any[] = [];
// first of all listen 'readable' event to catch all incoming request data
req
.on('readable', () => {
// read every incoming chunk. Every chunk is 64Kb data of Buffer
const chunk = req.read();
if (chunk !== null) {
buffers.push(chunk);
}
})
// listen on end event of request to send our data
.on('end', async () => {
try {
const result = await fetch('https://google.com/api/upload', {
method: 'POST',
credentials: 'include',
mode: 'cors',
headers: {
'Content-Type': req.headers['content-type'] ?? 'multipart/form-data',
'User-Agent': req.headers['user-agent'] ?? '',
Authorization: 'Bearer Token',
},
// concatination of array of Buffers and store it to body
body: Buffer.concat(buffers),
});
const body = await result.json();
setCookies(res, result.headers);
res.status(result.status).json(body);
return;
} catch (error) {
res.status(500).json(error);
}

res.status(405);
res.send('Method Not Allowed');
});
};
export default handler;

关于node.js - 代理在 NextJS(也是 NodeJS)中传递 multipart,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70084915/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com