To create two Post End Points in the same file using Next.js, you can follow the steps below:
NextApiRequest
and NextApiResponse
from next
.import type { NextApiRequest, NextApiResponse } from 'next'
export default function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method === 'POST') {
const { type } = req.body
if (type === 'user') {
createUser(req, res)
} else if (type === 'post') {
createPost(req, res)
} else {
return res.status(400).json({ error: 'Unknown type' })
}
} else {
return res.status(400).json({ error: 'Invalid method' })
}
}
async function createUser(req: NextApiRequest, res: NextApiResponse) {
// handle creating user
}
async function createPost(req: NextApiRequest, res: NextApiResponse) {
// handle creating post
}
useRouter
hook to test your endpoints. For example, you can use a tool such as curl
or Postman
to test the End Points. For the "createUser" endpoint, you would send a POST request to /api/myEndpoint
with a type
parameter of user
. Similarly, for the "createPost" endpoint, you would send a POST request to /api/myEndpoint
with a type
parameter of post
.curl -X POST -H "Content-Type: application/json" -d '{"type": "user"}' http://localhost:3000/api/myEndpoint
curl -X POST -H "Content-Type: application/json" -d '{"type": "post"}' http://localhost:3000/api/myEndpoint
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-05-16 11:00:00 +0000
Seen: 13 times
Last updated: Nov 02 '21
How can JSON be decoded while using a universal interface as a field?
How can a new object with a specific type be created in Angular 2 using the domain model?
What is a more effective method to verify the type of an Array containing elements of any type?
How can I remove items from the Symfony dropdown form type?
How can I create a new table by changing the current table type?
How can the project type be modified from a class library to a WPF User control library?
How do you type hint a decorator that modifies the function parameters or signature?