admin管理员组文章数量:1430863
I am trying to access params in my Next.js API routes. I am just wondering why in order to access a certain dynamic route id
I must use req.query
when normally in express I would access the id
via params
. Is req.query
the correct way of accessing the id
?
I have the following api folder structure.
/pages
/api
/posts
-index.js
-[postId].js
In my [postId]
file I have the following
function handler(req, res) {
// shows undefined
console.log(req.params);
const postId = req.params.postId;
and my api call is as follows:
fetch(`/api/posts/${id}`)
I am trying to access params in my Next.js API routes. I am just wondering why in order to access a certain dynamic route id
I must use req.query
when normally in express I would access the id
via params
. Is req.query
the correct way of accessing the id
?
I have the following api folder structure.
/pages
/api
/posts
-index.js
-[postId].js
In my [postId]
file I have the following
function handler(req, res) {
// shows undefined
console.log(req.params);
const postId = req.params.postId;
and my api call is as follows:
fetch(`/api/posts/${id}`)
Share
Improve this question
asked May 8, 2022 at 3:37
Dylan L.Dylan L.
1,3173 gold badges21 silver badges42 bronze badges
1
-
The docs say that to access the id, you need to use
req.query
– Tanay Commented May 8, 2022 at 4:17
1 Answer
Reset to default 4Referring to nextJs docs, all examples uses req.query
to get the id or other parameters:
import { useRouter } from 'next/router'
const Post = () => {
const router = useRouter()
const { pid } = router.query
return <p>Post: {pid}</p>
}
export default Post
So there's nothing wrong with this approach.
Nextjs doesn't explicit says why they use query
instead of params
, but in the section about dynamic routes you can get some clues:
the route /post/abc?foo=bar will have the following query object:
{ "foo": "bar", "pid": "abc" }
Probably they use query as a way to join both params and query in one object or it's just more convenient to use that way, so as there's no reference about it you don't have to care that much, just use the query and be happy.
本文标签: javascriptusing reqparams vs reqquery in Nextjs dynamic api routesStack Overflow
版权声明:本文标题:javascript - using req.params vs req.query in Next.js dynamic api routes - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745566418a2663787.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论