You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过koa-router获取DELETE请求的Query参数?

Fix: Koa-router Can't Fetch Query Params from Axios DELETE Request

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:

  1. Update your koa-router definition:
    router.delete('/delete/:category/:id', deleteOneComment);
    
  2. Modify your Axios request to use path variables:
    Axios({ 
      method: 'DELETE', 
      url: `http://localhost:3001/delete/${category}/${id}`
    })
    
  3. Now you can use ctx.params in your handler to get category and id, since they’re part of the route path.

内容的提问来源于stack exchange,提问作者frankkai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:54:30