乐闻世界logo
搜索文章和话题

How to handle a post request in next js

2个答案

1
2

Next.js is a React-based framework optimized for server-side rendering and static site generation. It handles HTTP requests primarily through two methods:

  1. API Routes: Next.js allows you to create API routes in the /pages/api directory, which can handle HTTP requests including POST requests. These route files execute on the server, where you can implement logic to receive and process POST requests.

    For example, to create a POST request handler for user registration, create a register.js file in the /pages/api directory:

    javascript
    // pages/api/register.js export default function handler(req, res) { if (req.method === 'POST') { // Extract data from the request body const { username, password } = req.body; // Implement registration logic here, such as validation and database saving // ... // Return a successful response res.status(200).json({ message: 'User registered successfully!' }); } else { // For non-POST requests, return 405 Method Not Allowed res.setHeader('Allow', 'POST'); res.status(405).end(`Method ${req.method} Not Allowed`); } }

    When a client sends a POST request to /api/register, Next.js automatically invokes this handler.

  2. getServerSideProps or getInitialProps: These functions run server-side before page rendering and are primarily used for data fetching in server-side rendering scenarios, not for directly handling POST requests. However, you can inspect the context or req object to detect POST requests and execute logic accordingly, though this is not their intended purpose.

The recommended approach for handling POST requests is to use API routes. This approach separates business logic into dedicated API endpoints, resulting in clearer frontend and backend separation, and keeps frontend pages concise by eliminating the need to handle HTTP request details directly.

2024年6月29日 12:07 回复

To make POST requests work in Next.js API routes, you may need to do three things.

  • Restrict the method to POST
  • Use JSON.parse() to parse JSON in the route (not needed in Next.js v12+)
  • Send a request to the backend

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

API Routes

Next.js API routes natively support all types of requests, including GET, POST, DELETE, etc. While not strictly necessary, it's best to restrict the route to the methods you intend to support.

For your specific case, if you only want to support POST requests on a particular route, you can filter out non-POST requests using req.method.

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

To parse JSON, you can use JSON.parse(). If you're using Next.js v12+, this is not needed unless you've set bodyParser: false.

javascript
const body = JSON.parse(req.body)

Putting it all together, your API route should look like this:

javascript
// 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 Next.js v12+ const body = JSON.parse(req.body) // the rest of your code }

Sending Requests

Finally, you need to send a POST request from your frontend code to the backend. While you may already know how to do this, it's mentioned for completeness.

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

By the way, you don't need to worry about fetch's cross-browser compatibility with Next.js. Next.js automatically adds a polyfill when needed (see here).

2024年6月29日 12:07 回复

你的答案