Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get koa-router query params?

Tags:

node.js

koa2

I haved used axios.delete() to excute delete in frontend ,code like below

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

And I used koa-router to parse my request in backend ,but I can't get my query params.

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)

Could anyone give me a hand ?

like image 461
frankkai Avatar asked Apr 05 '18 02:04

frankkai


2 Answers

You can use ctx.query and then the name of the value you need.

For instance, for the given url:

https://hey.com?id=123

You can access the property id with ctx.query.id.

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

    ctx.body = {
      id
    }
});
like image 184
Diego Fortes Avatar answered Oct 30 '22 00:10

Diego Fortes


Basically, I think you misunderstood context.params and query string.

I assume that you are using koa-router. With koa-router, a params object is added to the koa context, and it provides access to named route parameters. For example, if you declare your route with a named parameter id, you can access it via params:

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

To get the query string pass through the HTTP body, you need to use ctx.request.query, which ctx.request is koa request object.

Another thing you should be aware with your code is essentially, a http delete request is not recommended to have a body, which mean you should not pass a params with it.

like image 42
Thai Duong Tran Avatar answered Oct 30 '22 01:10

Thai Duong Tran