gpt4 book ai didi

Next js Api routing(下一个JS Api路由)

转载 作者:bug小助手 更新时间:2023-10-25 14:03:16 29 4
gpt4 key购买 nike



I am working with Next js 13.4 and trying to send id of a product with query parameters as -
http://localhost:3000/api/abc/abc/update/89?id=2

我正在使用Next js13.4,并尝试将带有查询参数的产品id发送为-http://localhost:3000/api/abc/abc/update/89?id=2


The code i wrote-

我写的代码-


export async function PUT(req,res){
console.log(req.query);
return NextResponse.json('hi');
}

I am getting response perfectly but I want to log id from url and I tried using - const {id} = req.query but it shows cannot destructure id as it is undefined. Is there any way I can get that id? Without splitting the url. Main thing is I want to know why req.query is giving undefined? It should give 2.

我得到了完美的响应,但我想从url登录id,我尝试使用-const{id}=req.query,但它显示无法分解id,因为它是未定义的。有没有办法让我拿到那个身份证?而不拆分URL。主要是我想知道为什么Req.Query给出未定义的?它应该给2。


更多回答

Does this answer your question? Get url params in API route handler in Next.js

这回答了你的问题吗在Next.js中获取API路由处理程序中的url参数

优秀答案推荐

Route handlers in the App router function differently compared to the previous pages API.

与前面的页面API相比,App路由器中的路由处理程序的运行方式有所不同。


You've written:

你写道:


export async function PUT(req, res) {

Note that the second parameter should be the context rather than the response object.

请注意,第二个参数应该是上下文,而不是响应对象。


Backing to your original question on how to access query parameters in the app router, you can achieve this using either of the following methods:

回到您最初关于如何在应用程序路由器中访问查询参数的问题,您可以使用以下方法之一来实现这一点:


1:


const searchParams = req.nextUrl.searchParams;
const id = searchParams.get("id");

2:


const { searchParams } = new URL(request.url);
const id = searchParams.get('id');

更多回答

I tried this but I was missing searchparams.get. Now this is working Thanks.

我试过了,但我错过了搜索参数。现在,这起作用了,谢谢。

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com