9

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 ?

frankkai
  • 145
  • 1
  • 2
  • 9

3 Answers3

12

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.

Thai Duong Tran
  • 2,453
  • 12
  • 15
4

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
    }
});
Diego Fortes
  • 8,830
  • 3
  • 32
  • 42
0

per koa documentation ctx.request.query

Rajat banerjee
  • 1,781
  • 3
  • 17
  • 35