如何在nextjs中间件中获取params



我有一个中间件,可以在每个请求时触发。如何获取url中的id?如果它像这个

http://localhost:3000/dash/profile/103848028402840http://localhost:3000/dash/home/103848028402840;http://localhost:3000/dash/notification/103848028402840

我不能拆分profile,因为下次中间件运行时,它不会是profile,而是home。

和〔middleware〕.js也不会工作,对吧?

最好的解决方案是使用Next Catch all路由功能

您需要将文件名更改为[...middleware].js,因为Rest Parameters将帮助您访问url中的数据。

然后在页面中,你可以像一样

import { useRouter } from "next/router";
export default function CustomPage() {
const router= useRouter()
console.log(router.query)
const {params = []} = router.query
// you will get all the data in params array and last index will be id
console.log(params[2])  
}

最新更新