Search code examples
javascriptreactjsnode.jsexpresscors

Problems with fetching data on Express server


I created NodeJS server with Express.js and now I'm trying to make a request for it by fetch.

fetch("http://localhost:3001/api", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(formData),
  })
    .then((response) => response.json())
    .then((data) => {
      if (data.user) {
        alert(`Welcome, ${data.user.name}!`);
      } else {
        alert("User not found!");
      }
    })
    .catch((error) => {
      alert("Error fetching data:" + error);
    });

This is server part:

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');

const app = express();
app.use(cors());
app.use(bodyParser.json());

const users = {
  AG0n1: {
    name: "AG0n1",
    status: "admin",
    email: "mmarkovec15072003@gmail.com",
    password: "111",
    phoneNumber: "+375293883088",
  },
  Teacher: {
    name: "Teacher",
    status: "admin",
    email: "admin",
    password: "test",
    phoneNumber: "+375293883088",
  },
  User: {
    name: "User",
    status: "user",
    test: "test",
  },
};

app.post('/api', (req, res) => {
  console.log("Received a POST request");
  const { email, password } = req.body;
  const user = Object.values(users).find((u) => u.email === email && u.password === password);
  if (user) {
    console.log(user)
    res.json({ user });
  } else {
    res.status(401).json({ error: 'Invalid credentials' });
  }
});


app.get('/api', (req, res) => {
  res.json(users);
});

But sometimes at random moment I get the following error: Error fetching data:TypeError: Failed to fetch

At first glance, there seems to be no pattern to this error. Sometimes I get the expected result and sometimes this error. Can you help me to solve this problem?

ChatGPT said that my code is normal and that I used middleware 'cors()'. He didnt help me so i decided to ask this question here.


Solution

  • This could be an issue with the response you are receiving from the backend. If it was working fine on the server then the problem could be within the response headers.

    Check the value of Access-Control-Allow-Origin in the response headers. Usually fetch API will throw fail to fetch even after receiving a response when the response headers' Access-Control-Allow-Origin and the origin of request won't match.