我想在我的next.js api文件夹中设置一个
POST
路由,我将数据发送到该路由,但无法解析数据以实际保存到数据库中。如何处理next.js中的POST
路由是最好的方式,特别是以JSON
格式解析数据?POST
路由,我将数据发送到该路由,但无法解析数据以实际保存到数据库中。如何处理next.js中的POST
路由是最好的方式,特别是以JSON
格式解析数据?要在Next.js API路由中使POST请求正常工作,您需要执行以下3个步骤:
POST
JSON.parse()
解析路由中的JSON(在NextJS v12+中不需要)https://nextjs.org/docs/api-routes/api-middlewares
Next.js中的API路由默认支持所有类型的请求,包括GET、POST、DELETE等。因此虽然不是必需的,但将路由限制为您想要支持的方法是一个好主意。
在您的情况下,如果您只想支持某个路线上的POST
请求,则可以使用req.method
来过滤非POST请求。
if (req.method !== 'POST') {
res.status(405).send({ message: 'Only POST requests allowed' })
return
}
为了解析JSON,你可以使用JSON.parse()
。如果你正在使用NextJS V12+,并且没有设置bodyParser: false
,则不需要这样做。const body = JSON.parse(req.body)
把所有东西结合起来,你的API路由应该像这样:
// pages/route-name.js
export default function handler(req, res) {
if (req.method !== 'POST') {
res.status(405).send({ message: 'Only POST requests allowed' })
return
}
// not needed in NextJS v12+
const body = JSON.parse(req.body)
// the rest of your code
}
最后,您需要从前端代码向后端发送POST请求。您可能已经知道如何做到这一点,但为了完整起见还是提一下。
fetch('/api/route-name', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(objectWithData),
})
简要说一下,您不需要为在Next.js中使用fetch
而担心跨浏览器兼容性问题。Next.js会在需要时自动添加polyfill。
bodyParser: false
(请参见 https://nextjs.org/docs/api-routes/api-middlewares),则不需要在 API 路由中使用 JSON.parse(req.body)
。例如,如果请求的 content-type
是 application/json
,那么 req.body
将自动解析为一个对象。在这种情况下,由于内容已经被预先解析成了对象,尝试在 API 中运行 JSON.parse(req.body)
很可能会抛出错误。fetch
发送请求,请记得将 Content-Type
设置为 application/json
,否则 Next.js 不会自动解析。 - Sandro Maglioneimport { NextResponse } from 'next/server'
export async function POST() {
const res = await fetch('https://data.mongodb-api.com/...', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'API-Key': process.env.DATA_API_KEY,
},
body: JSON.stringify({ time: new Date().toISOString() }),
})
const data = await res.json()
return NextResponse.json(data)
}
要获取最新的和现成的路由处理程序模板以及更多内容,请使用 Next.js 13+ 强大代码片段 | TypeScript/Javascript
res.json()
时,不要忘记使用await
。 - undefined
/cars
,但是POST /cars
和NextJS使用其SSR功能来呈现页面,其中使用getServerSideProps(...)
来编写从外部API获取数据的逻辑。 - shashwatPost
请求等同于向页面发送请求。https://vercel.com/docs/concepts/limits/overview#serverless-functions-created-per-deployment - NickContent-Type: application/json
(适用于 Next.js v12+)。 - 1antares1