【问题标题】:I cant get a response from a POST request with an array in the body, Using NodeJS / Axios and Postman使用 NodeJS / Axios 和 Postman,我无法从正文中包含数组的 POST 请求中获得响应
【发布时间】:2022-01-17 11:26:33
【问题描述】:

这是一个课程测验,这是我创建 React 应用程序所需的最基本信息。但是,虽然端点 URL 正确,但当我尝试请求产品列表时,页面“/products”会返回“400”错误。我得到的指示是:

获取产品列表

  • 路线:/products
  • 主体:数组
  • 方法:POST
{
  "product-codes": [
    "98798729",
    "84876871",
    "29879879",
  ]
}

我的 index.js

...

app.post(`/products`, async (req, res) => {
  try {
    const response = await axios.post(`${apiURL}/products`);
    // console.log(response.data);
    res.status(200).json(response.data);
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
});

在邮递员中
我使用 http://localhost:4000/products
并传递一个 Body / Raw /JSON:

{
  "product-codes": [
    "98798729",
    "84876871",
    "29879879",
  ]
}

但我进不去!我没有看到明显的东西,因为这是一个非常漫长而复杂的测验的入口点。谢谢

【问题讨论】:

  • 你没有在请求体中传递数组 const response = await axios.post(${apiURL}/products, data);
  • ` const response = await axios.post(${apiURL}/products);` 这是一个发布请求,您没有向它传递任何正文。查看axios的post版本,需要传递body来接收。
  • 谢谢@zabusa,但我以为我是在使用 Postman 传递尸体,我必须通过 axios 和 Postman 发送它才能得到回复吗?
  • 也感谢@ApoorvaChikara。我正在使用邮递员。
  • 是的,如果您不将 body 传递给 axios,则不会返回任何内容。

标签: node.js axios postman


【解决方案1】:

我从代码中看到的是一个递归的长调用。

app.post(`/products`, async (req, res) => {
  try {
    const response = await axios.post(`${apiURL}/products`); // calling the same end point 
    // console.log(response.data);
    res.status(200).json(response.data);
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
});

你应该这样做:

app.post(`/products`, async (req, res) => {
    // do your logic
    // when you pass body from postman on this endpoint
   // you will receive the body here and save it to DB
   // or do the manipulation and then send back the response
    res.status(200).json(req.body.data);
});

我强烈建议您先阅读一些教程以了解 API 的工作原理以及如何使用 Node.jscreate simple API

【讨论】:

  • 谢谢 Apporva。你帮我过线了。是的,我将执行操作产品 ID 的逻辑,但我只是想让它首先工作,以便我可以继续。我在上一步中有“axios.get(...)”而不是 axios.post(...)"。现在它可以工作了,我可以移动一个...直到出现下一个问题。我会听取你的建议并继续查看教程。
猜你喜欢
  • 2022-01-08
  • 2020-04-29
  • 2021-02-02
  • 2020-09-01
  • 2013-04-02
  • 1970-01-01
  • 1970-01-01
  • 2020-07-07
  • 1970-01-01
相关资源
最近更新 更多