Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
React cannot fetch data from Express

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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!

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!