简体   繁体   English

获取 Next.js API 上的路径参数

[英]Get path parameter on Next.js API

I have the following file我有以下文件

pages/api/[slug]/[uid].ts

And I want to get the slug and the uid on the body of my handler, how can I do it?我想在我的处理程序身上获取sluguid ,我该怎么做?

You can access it with req.query Just console.log it and see docs for more https://nextjs.org/docs/api-routes/dynamic-api-routes您可以使用req.query访问它只需 console.log 并查看文档以获取更多https://nextjs.org/docs/api-routes/dynamic-api-routes

You can make use of the useRouter() custom hook provided by the next for accessing query params in NextJs.您可以利用 next 提供的useRouter()自定义钩子来访问 NextJs 中的查询参数。 It will return an object which will contain details of the url loaded, including the query params.它将返回一个 object,其中将包含加载的 url 的详细信息,包括查询参数。 The params will be stored within query key in the returned object.参数将存储在返回的 object 中的query键中。 The query itself has an object as value, where key is the param name (here slug and uid ) and its dynamic values as the values. query本身有一个 object 作为值,其中 key 是参数名称(这里是sluguid ),它的动态值作为值。

Then we can make use of the object destructuring for drilling into the required params.然后我们可以利用 object 解构来钻取所需的参数。

  const router = useRouter();
  const { slug, uid } = router.query;

For accessing single param, we can do as follows,对于访问单个参数,我们可以执行以下操作,

  const router = useRouter();
  const slugValue = router.query.slug;
  const uidValue = router.query.uid;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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