繁体   English   中英

如何处理 next.js 中的 post 请求?

[英]how to handle a post request in next.js?

我想使用 next.js 在我的 api 文件夹中设置一个POST路由,并且我正在将数据发送到路由,但我无法解析数据以将其实际保存在数据库中。 在 next.js 中处理POST路由的最佳方法是什么。 特别是解析JSON格式的数据?

要让 POST 请求在 Next.js API 路由中工作,您可能需要做 3 件事。

  • 将方法限制为POST
  • 使用JSON.parse()解析路由中的 JSON (在 NextJS v12+ 中不需要)
  • 向后端发送请求

https://nextjs.org/docs/api-routes/api-middlewares

API 路线

Next.js 中的 API 路由默认支持所有类型的请求,包括 GET、POST、DELETE 等。因此,虽然不是必需的,但最好将路由限制为您想要支持的方法。

在您的情况下,如果您只想支持某个路由上的POST请求,您可以使用req.method过滤掉非发布请求。

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。

与所有事情一样,这取决于。 In Next.js v12, you do not need JSON.parse(req.body) in the API route as long as you have NOT explicitly set bodyParser: false in the exported configuration for the API route (see https://nextjs.org/docs /api-routes/api-middlewares )。 req.body将被自动解析为 object 例如,如果请求的content-typeapplication/json 在这种情况下,由于内容被预解析为 object,因此尝试在 API 中运行JSON.parse(req.body)可能会引发错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM