Home > Back-end >  I cant get a response from a POST request with an array in the body, Using NodeJS / Axios and Postma
I cant get a response from a POST request with an array in the body, Using NodeJS / Axios and Postma

Time:12-15

This is a course quiz and this is the most basic information I need in order to create a React app. But while the endpoint URL is correct, the page "/products" returns a "400" error when I try to request the product list. The instructions I'm given are:

Obtain a list of products with

  • Route: /products
  • Body: Array
  • method: POST
{
  "product-codes": [
    "98798729",
    "84876871",
    "29879879",
  ]
}

My 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 });
  }
});

in Postman
I use http://localhost:4000/products
and pass a Body / Raw /JSON:

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

But I can't get in! I am not seeing something obvious because this is the entry point to a very long and complex quiz. Thanks

CodePudding user response:

What I see from the code is a recursive long call.

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 });
  }
});

You should do something like this:

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);
});

I highly recommend you to first follow through some tutorials to understand how API works and how to create simple API using Node.js.

  • Related