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

Next js - How to pass multiple parameters in url for api?

1个答案

1

In Next.js, passing multiple parameters to API routes typically involves two methods: Query Strings and Dynamic Routes. Below, I will detail both methods with examples.

1. Query Strings

Query strings are part of the URL used to pass query parameters. In Next.js, you can send requests with query parameters by using fetch or other HTTP client libraries (such as axios) within your pages.

Example:

Assume you have an API route named api/users and you want to filter users based on username and age. You can construct a request like this:

js
// Within a page or other client-side code fetch(`/api/users?username=${encodeURIComponent(username)}&age=${encodeURIComponent(age)}`) .then(response => response.json()) .then(data => { // Process your data });

In this request, username and age are query parameters passed to the /api/users route.

In the API route, you can retrieve these parameters as follows:

js
// In pages/api/users.js export default function handler(req, res) { const { query } = req; const { username, age } = query; // Process your logic based on username and age res.status(200).json({ /* Your response data */ }); }

2. Dynamic Routes

Dynamic routes allow you to define variables based on parts of the URL path. This is useful when you want to create API routes based on specific path parameters.

Example:

If you want to fetch a specific post using a user ID and post ID, you can create a dynamic route like /api/users/[userId]/posts/[postId].

In Next.js, you would structure your files as follows:

shell
pages/ api/ users/ [userId]/ posts/ [postId].js

In the [postId].js file, you can retrieve the dynamic path parameters as follows:

js
// In pages/api/users/[userId]/posts/[postId].js export default function handler(req, res) { const { query } = req; const { userId, postId } = query; // Process your logic using userId and postId res.status(200).json({ /* Your response data */ }); }

Client-side code would be:

js
// Using template literals to construct the URL fetch(`/api/users/${userId}/posts/${postId}`) .then(response => response.json()) .then(data => { // Process the data });

In this case, userId and postId are part of the URL path, not query string parameters.

These are the two primary methods for passing multiple parameters to API routes in Next.js. In practice, choose the method that best fits your specific needs.

2024年6月29日 12:07 回复

你的答案