【问题标题】:send body with "GET" method in axios在 axios 中使用“GET”方法发送正文
【发布时间】:2021-11-29 19:19:53
【问题描述】:

在 axios 中有没有用GET 方法发送正文?因为在postman 中是可能的。我的后端代码如下:

我正在使用express.js + sequelize

const c_p_get_all = async (req, res) => {
const { category } = req.body;
const sql = `select p.id, p.p_image, p.p_name, p.p_desc, p.p_prize, p.p_size, c.c_name, cl.cl_name
  from products as p
  inner join collections as cl on cl.id = p.p_collection_id 
  inner join categories as c on c.id = cl.cl_category_id
  where c.c_name = ?
  order by p."createdAt" desc;`;
 
try {
  const getData = await Product.sequelize.query(sql, {
    replacements: [category],
  });
   if (getData[0] != "") {
     res.status(200).send({
      s: 1,
      message: "success retrive all products",
      data: getData[0],
     });
   } else {
     res.status(404).send({
      s: 0,
      message: "data not found",
  });
  }
 } catch (err) {
   res.status(500).send({
     message: err,
  });
 }
};

我的前端与react.js + axios

const test = "woman";
axios({
  headers: {
    "content-type": "application/json",
  },
  method: "GET",
  url: "http://localhost:3001/api/v1/product",
  data: { category: test },
})
  .then((value) => console.log(value))
  .catch((error) => console.log(error.response));

它总是转到status 404,但在postman 它的工作中,我试图搜索这个问题,但没有任何线索。那么有没有办法在 axios 中做到这一点,或者我应该将我的后端更改为POST 方法还是将req.body 更改为req.query

【问题讨论】:

  • 即使可以在 GET 请求中添加正文,这也是非标准的,通常是个坏主意。在我看来,最好将后端更改为 POST,或者只是在查询参数中发送数据(例如 localhost:3001/api/v1/product?category=test`)
  • @ippi 是的,我想我会通过使用查询参数来接受您的建议,因为我发现从 axios 文档中它不允许使用 GET 方法发送正文。感谢您的建议...

标签: node.js rest axios


【解决方案1】:

我改成查询参数,效果很好

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2019-08-29
  • 2019-05-29
  • 1970-01-01
  • 1970-01-01
  • 2020-05-21
  • 2020-08-24
相关资源
最近更新 更多