如何获取Koa路由器查询参数?

fra*_*kai 3 node.js koa2

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

Axios({
    method: 'DELETE',
    url:'http://localhost:3001/delete',
    params: {
        id:id,
        category:category
    }
})
Run Code Online (Sandbox Code Playgroud)

而且我使用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)
Run Code Online (Sandbox Code Playgroud)

有人可以帮我吗?

Tha*_*ran 5

基本上,我想你是误会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]' }
});  
Run Code Online (Sandbox Code Playgroud)

要使查询字符串通过HTTP正文传递,您需要使用ctx.request.query,这ctx.request是koa请求对象。

从本质上讲,您还应该注意的另一件事是,不建议使用http delete请求具有正文,这意味着您不应将其传递给a params