Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

177
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda