简体   繁体   中英

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

I am able to pass one parameter and get results from next js api

The docs are very helpful - https://nextjs.org/docs/api-routes/dynamic-api-routes

/api/posts/[postId].js

The above works but is there an option to pass another parameter like below?

/api/posts/[postId][userId].js

The folder name is currently [postId]. I tried renaming it to [postId][userId]

My code for api is

  let postVotes = await req.db.collection('votesPosts').count({"post":req.query.postId,"user":req.query.userId})

Usually, routes don't handle multiple parameters in a single segment of the URL path. You can only have one parameter per segment:

/api/entity/{param1}/{param2}/sub/{param3}

Now in Next JS, you need to separate them too to have 2 segments with param:

/api/posts/[postId]/[userId]

Which would resolve to 2 possible files:

/api/posts/postId]/[userId]/index.js

if you do it with a parameter directory + index file, or

/api/posts/postId]/[userId].js

if you do it with a parameter file.

Doing it with directory + index file allow you to add fixed segments like:

/api/posts/postId]/[userId]/popular.js
/api/posts/postId]/[userId]/private.js

Then you can make your API call as you did it for 2 params.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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