Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to handle a post request in next.js?

I want to setup a POST route in my api folder using next.js, And I'm sending the data to the route but I can't parse the data to actually save it in the database. what is the best way to handle POST routes in next.js. particularly parsing the data in JSON format?

like image 740
Dastan Avatar asked Mar 22 '21 03:03

Dastan


People also ask

Why you shouldn't use NextJS?

Disadvantages of NextJS Although NextJS is developing rapidly and many features arrive, it still has some cons and issues which you can see below: Cost of flexibility – Next JS does not provide many built-in front pages, so you have to create the whole front-end layer from the ground up.

Can we write API in NextJS?

Next. js lets you create an API endpoint as a Node. js serverless function. 💡 Any file inside the folder pages/api is mapped to /api/* and will be treated as an API endpoint instead of a page .

Does NextJS replace Express?

Next. js doesn't replace Express and you can use them together. Next. js uses some Node.

How to send a POST request using jQuery?

You can also send a post request using the new Fetch API method. jQuery users can send post requests using the jQuery.post () method. Click Execute to run JavaScript POST Request Example online and see the result. What is JavaScript? JavaScript is scripting used both on the client-side (in browsers) and the server-side (NodeJs).

How do I make a route only support post requests?

API routes in Next.js by default support all types of requests, including GET, POST, DELETE, etc. So while it isn't required, it's a good idea to restrict the route to the methods you want to support. In your case, if you want to only support POST requests on a certain route, you use req.method to filter out non-post requests.

How do I send an HTTP POST request using XMLHttpRequest?

To send an HTTP POST request, we need to first create the object by calling new XMLHttpRequest () and then use the open () and send () methods of XMLHttpRequest. To receive notifications when the status of a request has changed, we need to subscribe to the onreadystatechange event.

How do I create a REST API for my next app?

You can easily create a REST API for your Next.js app by using the built-in API routes. This article will show an example of how this API can be created. REST is a set of architectural constraints. It is neither a protocol nor a standard. API developers can implement REST in a number of ways.


1 Answers

To get POST requests working in Next.js API routes, you likely want to do 3 things.

  • Limit the method to POST
  • Use JSON.parse() to parse the JSON on in the route
  • Send a request to the backend

API Route

API routes in Next.js by default support all types of requests, including GET, POST, DELETE, etc. So while it isn't required, it's a good idea to restrict the route to the methods you want to support.

In your case, if you want to only support POST requests on a certain route, you use req.method to filter out non-post requests.

if (req.method !== 'POST') {
  res.status(405).send({ message: 'Only POST requests allowed' })
  return
}

To parse the JSON, all you can use JSON.parse().

const body = JSON.parse(req.body)

Put it all together, and your API route should look something like this:

// pages/route-name.js

export default function handler(req, res) {
  if (req.method !== 'POST') {
    res.status(405).send({ message: 'Only POST requests allowed' })
    return
  }

  const body = JSON.parse(req.body)

  // the rest of your code
}

Send the request

Lastly, you need to send a POST request from your front-end code to the backend. You may already know how to do this, but mentioning this for completeness.

fetch('/api/route-name', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(objectWithData),
})

Quick aside, you don't need to worry about cross-browser compatibility for fetch with Next.js. Next.js automatically adds a polyfill when needed.

like image 150
Nick Avatar answered Oct 01 '22 03:10

Nick