如何通过koa-router获取DELETE请求的Query参数?
Alright, let's break down why your backend isn't picking up those parameters. The core issue here is a mix-up between two different Koa context properties: ctx.params and ctx.query.
What Went Wrong
You’re using ctx.params in your Koa handler, but that’s meant for route path parameters—the placeholder values you define in your router, like /delete/:id where :id is a param pulled directly from the URL path.
But your Axios request is sending URL query parameters (the ?id=xxx&category=yyy part at the end of the URL). In Koa, these live in ctx.query, not ctx.params. That’s why console.log(ctx.params) was probably showing an empty object!
Quick Fix for Your Backend Code
Just swap out ctx.params with ctx.query, and you’ll be good to go. Here’s your updated handler:
const deleteOneComment = (ctx, next) => { // Grab query params from ctx.query instead of ctx.params const { id, category } = ctx.query; console.log(ctx.query); // Now this will log { id: "your-id", category: "your-category" } try { db.collection(`${category}mds`).deleteOne({ "_id": ObjectId(id) }); // Don't forget to send a success response back to the frontend! ctx.status = 200; ctx.body = { success: true, message: "Item deleted successfully" }; } catch (err) { // Handle errors properly so the frontend knows what went wrong ctx.status = 500; ctx.body = { success: false, error: err.message }; } };
Check Your Frontend Request (It’s Actually Fine!)
Your Axios DELETE code is totally correct:
Axios({ method: 'DELETE', url:'http://localhost:3001/delete', params: { id: id, category: category } })
Axios automatically takes the params object and turns it into the query string at the end of your URL, so the final request hits http://localhost:3001/delete?id=your-id&category=your-category—exactly what you need.
Bonus: Using Route Params Instead (If You Prefer)
If you’d rather structure your URL with path parameters (like /delete/your-category/your-id), here’s how to adjust:
- Update your koa-router definition:
router.delete('/delete/:category/:id', deleteOneComment); - Modify your Axios request to use path variables:
Axios({ method: 'DELETE', url: `http://localhost:3001/delete/${category}/${id}` }) - Now you can use
ctx.paramsin your handler to getcategoryandid, since they’re part of the route path.
内容的提问来源于stack exchange,提问作者frankkai

