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 ?
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
}
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With