繁体   English   中英

如何获取 koa-router 查询参数?

[英]How to get koa-router query params?

我已经使用 axios.delete() 在前端执行删除,代码如下

Axios({
    method: 'DELETE',
    url:'http://localhost:3001/delete',
    params: {
        id:id,
        category:category
    }
})

我使用 koa-router 在后端解析我的请求,但我无法获得我的查询参数。

const deleteOneComment = (ctx,next) =>{
    let deleteItem = ctx.params;
    let id = deleteItem.id;
    let category = deleteItem.category;
    console.log(ctx.params);
    try {
        db.collection(category+'mds').deleteOne( { "_id" : ObjectId(id) } );
}
route.delete('/delete',deleteOneComment)

谁能帮我一把?

基本上,我认为您误解了context.paramsquery string

我假设您正在使用koa-router 使用koa-router ,一个params对象被添加到 koa context ,它提供对named route parameters访问。 例如,如果您使用命名参数id声明路由,则可以通过params访问它:

router.get('/delete/:id', (ctx, next) => {
  console.log(ctx.params);
  // => { id: '[the id here]' }
});  

要通过 HTTP body 获取查询字符串,您需要使用ctx.request.query ,其中ctx.request是 koa 请求对象。

您在代码中应该注意的另一件事本质上是,不建议 http 删除请求具有正文,这意味着您不应该使用它传递params

您可以使用ctx.query然后使用您需要的值的名称。

例如,对于给定的 url:

https://hey.com?id=123

您可以使用ctx.query.id访问属性id

router.use("/api/test", async (ctx, next) => {
    const id = ctx.query.id

    ctx.body = {
      id
    }
});

根据koa 文档ctx.request.query

暂无
暂无

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

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