Home > Enterprise >  Cant get data from express server
Cant get data from express server

Time:10-01

I am trying to send a GET request and receive a response on my client side (react).

On my express server:

app.get('/', function (req, res) {
   res.send('Hey, I came from the express server');
})

When I use postman to sent the request I receive a good answer:

enter image description here

So I don't think the problem is with the server.

A problem:

When I try to send the request using react like this:

  const getData = () => {
    fetch("http://localhost:8081", {
      method: "GET",
      mode: 'no-cors'
    }).then(response => console.log(response));
  }

For some reason the response status is 0 and not 200 (I am receiving status code of 200 when checking this request with postman and also on the chrome network tab). In addition, if I try to print response.body it will be null.

The response:

body: (...)
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 0
statusText: ""
type: "opaque"
url: ""
[[Prototype]]: Response

What am I doing wrong here?

CodePudding user response:

You need to transfer your response to an text or json like:

  const getData = () => {
    fetch("http://localhost:8081", {
      method: "GET",
      mode: 'no-cors'
    }).then(response => response.json()).then(data => console.log(data))
  }

Besides .json() there are even more methods. Its everything written down in the docs. You just need to google it:

https://developer.mozilla.org/en-US/docs/Web/API/Response#methods

CodePudding user response:

You can add a proxy property to your package.json:

"proxy": "http://localhost:8081",

And then just use / as your fetch endpoint.

fetch('/'...
  • Related