0

I have many similar functions and those are working well, but this fetch is not receiving any response from the API.

const fetchPdtDetails = async (code) => {
  const url = `${api}data/pdtDetails`;
  const params = { data: code };

  const fetchData = await fetch(url, {
    method: "POST",
    cache: "no-cache",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(params),
  })
    .then((response) => {
      console.log(response);
    })
    .catch((err) => {
      console.log(err);
    });

  const data = await fetchData.json();
  console.log(data);
  return data;
};

This is not logging any response at all. Nothing in the console.

The server side is as shown below:

router.post("/pdtDetails", async (req, res) => {
  try {
    const code = req.body.data;

    if (code != "") {
      const sql = `SELECT name , category FROM product_master 
      WHERE code=$1`;

      const get = await pool.query(sql, [code]);
      console.log(get.rows); /* can see the data here*/
      res.json(get.rows);
    }
  } catch (err) {
    res.json(err.message);
  }
});
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Maya
  • 183
  • 1
  • 14

1 Answers1

1

Your fetchData should be undefined.

You need change your codes to:

try {
    const fetchData = await fetch({ ... });
    const data = fetchData.json();
    console.log(data);
    return data;
} catch (err) {
    console.log(err);
}

Reason is, if you use async/await like this:

const result = await anyPromiseFunction().then(resolveFunction)

The result will be the returned value of resolveFunction;

Yan
  • 854
  • 1
  • 8
  • 15