Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

178
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda