admin管理员组文章数量:1208155
I'd like to read fetch's body. Here's what I send:
fetch('/api/foo', {
method: 'POST',
body: new FormData(formRef.current),
});
And now I only need to parse the body. But I don't know how. I can't use FormData
on the server side, because it says ReferenceError: FormData is not defined
. And I can't also use forEach
like on the client.
What should I do?
export default function sendMail(req: NextApiRequest, res: NextApiResponse): void {
// console.log(req.body instanceof FormData);
// req.body.forEach(console.log);
console.log(req.body['name']);
res.status(200).json({});
}
I'd like to read fetch's body. Here's what I send:
fetch('/api/foo', {
method: 'POST',
body: new FormData(formRef.current),
});
And now I only need to parse the body. But I don't know how. I can't use FormData
on the server side, because it says ReferenceError: FormData is not defined
. And I can't also use forEach
like on the client.
What should I do?
export default function sendMail(req: NextApiRequest, res: NextApiResponse): void {
// console.log(req.body instanceof FormData);
// req.body.forEach(console.log);
console.log(req.body['name']);
res.status(200).json({});
}
Share
Improve this question
asked Mar 17, 2021 at 14:11
Ivan AdanenkoIvan Adanenko
5752 gold badges6 silver badges21 bronze badges
2
- Does this answer your question? POST multipart/form-data to Serverless Next.js API (running on Vercel / Now.sh) – fjc Commented Mar 17, 2021 at 14:15
- It doesn't work – Ivan Adanenko Commented Mar 17, 2021 at 14:44
2 Answers
Reset to default 17You could use formidable.
npm install formidable
Then in your code use
import { NextApiRequest, NextApiResponse } from 'next'
import { Formidable } from "formidable";
//set bodyparser
export const config = {
api: {
bodyParser: false
}
}
export default async (req: NextApiRequest, res: NextApiResponse) => {
const data = await new Promise((resolve, reject) => {
const form = new Formidable();
form.parse(req, (err, fields, files) => {
if (err) reject({ err })
resolve({ err, fields, files })
})
})
//return the data back or just do whatever you want with it
res.status(200).json({
status: 'ok',
data
})
}
If you are using route-handlers
of NextJS, you can do the following :
export async function POST(request: NextRequest) {
const formData = await request.formData();
const email = formData.get('email');
const password = formData.get('password');
return NextResponse.json({
message: 'Logged in successfully'
});
}
本文标签: javascriptHow to read FormData in NextJSStack Overflow
版权声明:本文标题:javascript - How to read FormData in NextJS - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738694033a2107266.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论