Home > Net >  React cannot fetch data from Express
React cannot fetch data from Express

Time:11-29

I'm learning React and Express with that said I am working on my learning application which just takes data from MySQL and then Visualize it.

So, I made simple express server with router:

//controllers.js
const getData = async (SQL) => {
  try {
    const data = await new Promise((resolve, reject) => {
      pool.query(SQL, (err, res) => {
        if (err) reject(err);
        else resolve(res);
      });
    });
    return data;
  } catch (err) {
    return err;
  }
};

//router.js 
router.get("/CB/fridge01", (req, res, next) => {
  let sql = "SELECT * FROM fridge01";
  getData(sql)
    .then((result) => res.json(result))
    .catch((err) => res.json(err));
});

//index.js
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use("/api", router);

app.get("/", (req, res) => {
  res.redirect("localhost:"   port   "/api/CB/fridge01");
});


app.listen(port, (error) => {
  error
    ? console.log(`An error occurred: ${error}`)
    : console.log(`The server has started at http://localhost:${port}`);
});

And then in my react component I just use ComponentDidMount to execute fecth api:

componentDidMount() {
     //192.168.88.169 is my local IP and port 8080 is setup in index.js
    fetch("192.168.88.169:8080/api/CB/fridge01", { method: "GET" })
      .then((res) => {
        res
          .json()
          .then((json) => {
            this.setState({ metrics: json });
          })
          .catch((err) => console.log(err));
      })
      .catch((err) => console.log(err));
}

and it gives me an error in console saying: SyntaxError: Unexpected token < in JSON at position 0

When I open my express with curl or postman or even browser, I get the same data:

[{"id":1,"recorded":"2021-11-22T11:16:22.000Z"}] 

these are just sample data i hardcoded into DB table

Thank you for your help and patience and please excuse my grammar skills.

CodePudding user response:

There was an issue with fetch API on react side. Instead of fetching data from 192.168.88.169:8080/... I was fetching from localhost:3000/192.168...

To fix this I put http protocol into fetching URL. (fetch("http://192..."))

Then I simply allowed CORS and voila!

  • Related