FKM*_*FKM 8 javascript api mongodb reactjs next.js
我能够传递一个参数并从下一个 js api 获取结果
这些文档非常有帮助 - https://nextjs.org/docs/api-routes/dynamic-api-routes
/api/posts/[postId].js
Run Code Online (Sandbox Code Playgroud)
上面的方法有效,但是是否可以选择传递另一个参数,如下所示?
/api/posts/[postId][userId].js
Run Code Online (Sandbox Code Playgroud)
文件夹名称当前为 [postId]。我尝试将其重命名为 [postId][userId]
我的 api 代码是
let postVotes = await req.db.collection('votesPosts').count({"post":req.query.postId,"user":req.query.userId})
Run Code Online (Sandbox Code Playgroud)
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}
Run Code Online (Sandbox Code Playgroud)
Now in Next JS, you need to separate them too to have 2 segments with param:
/api/posts/[postId]/[userId]
Run Code Online (Sandbox Code Playgroud)
Which would resolve to 2 possible files:
/api/posts/postId]/[userId]/index.js
Run Code Online (Sandbox Code Playgroud)
if you do it with a parameter directory + index file, or
/api/posts/postId]/[userId].js
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
Then you can make your API call as you did it for 2 params.