Ad

Fetching Data From Express.js API From React.js. Postman's Request Are Working

- 1 answer

can anyone help me with little problem? I have Express application which is completly working with requests from postman(adding, deleting, etc.) Now, I want to connect my client side(react.js) with the existing API using fetch metod.

I had errors: Without "no-cors" mode

App.js:121 POST http://localhost:3000/users/login net::ERR_ABORTED 400 (Bad Request)

With "no-cors"mode

Failed to load resource: the server responded with a status of 400 (Bad Request)

Request in App.js

  handleLogInClick = (email, password) => {
email = "[email protected]";
password = "qweasd123";
console.log("Trying to login ");
fetch("http://localhost:3000/users/login", {
  // mode: "no-cors",
  method: "POST",
  headers: {
    Accept: "application/json, text/plain, */*",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ email: email, password: password }),
  // body:({email:email, password:password})
})
  .then((res) => res.json())
  .then((data) => console.log(data));

};

This is a problem with passed body in fetch method? Or CORS problems on server? I 'dont know, maybe someone more experienced know the solution for this problem.

Route in node.js

router.post('/users/login', async (req, res) => {
try {
    const user = await User.findByCredentials(req.body.email, req.body.password)
    const token = await user.generateAuthToken()
    res.send({ user, token })
} catch (e) {
    res.status(400).send()
}

})

Screenshot from Postman

screenshot-postman

Thanks for help, this is my first post on StackOverflow :)

Ad

Answer

Just to add on, here's a quick glance of the default browser behavior.

CORS or Cross Origin Resource Sharing is blocked in modern browsers by default (in JavaScript APIs)

A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own.

An example of a cross-origin request: the front-end JavaScript code served from https://domain-a.com uses XMLHttpRequest to make a request for https://domain-b.com/data.json.

For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy.

Installing this extension on your browser will help unblock the CORS.

Ad
source: stackoverflow.com
Ad