0

I wrote a function that receives my list from the server (NODEJS) in the REACT language

        getList = () => {
       const request = new Request('http://localhost:3000/api/get');
  
       fetch(request, {method: 'GET',mode: 'no-cors',
        })
       .then((response) => console.log("response", response.JSON()));
        }

The request is being made but the returned value I receive in CONSOLE.LOG is:

          response Response {type: "opaque", url: "", redirected: false, status: 0, ok: 
          false, …}body: (...)bodyUsed: falseheaders: Headers {}ok: falseredirected: falsestatus: 
          0statusText: ""type: "opaque"url: ""__proto__: Response

This is the code on the server:

             const MyList=[
             {id:1,name:'to do list'},
             {id:2,name:'to sleep'},
             ]
             app.get('/api/get',(req,res)=>{
             res.send(MyList);
             });

Where is the values ​​of the list returned from the server ???

semicolon
  • 255
  • 1
  • 3
  • 11
  • 1
    The values you are looking for will be in `response.body`, you probably want to change `res.send` to `res.json`. Also response.json() returns a promise, so you will have to do a .then() after. https://developer.mozilla.org/en-US/docs/Web/API/Body/json – Max Stanley Jul 12 '20 at 15:43

3 Answers3

0

The data from the server can be accessible from response.body, however response.json() returns a promise, so you will have to do something like this:

getList = () => {
    const request = new Request('http://localhost:3000/api/get');

    fetch(request, {method: 'GET',mode: 'no-cors'})
    .then((response) => response.json().then(json => {
          console.log(json.body);
    });
}
Alex
  • 1,208
  • 16
  • 26
  • @semicolon Have you tried testing your API separately from your react application? I.e. through the use of Postman – Alex Jul 12 '20 at 16:52
0

I added .json to response:

      getList = () => {
      const request = new Request('http://localhost:3000/api/get');
  
      fetch(request, {method: 'GET',mode: 'no-cors' })
      .then((response) => console.log("response", response.json()));
      }

and received the following error:

     TobuyList.js:30 Uncaught (in promise) SyntaxError: Unexpected end of input
     at TobuyList.js:30
semicolon
  • 255
  • 1
  • 3
  • 11
0

In your server, change res.send to res.json

On the client side (taken from mozilla docs):

fetch('http://localhost:3000/api/get', { mode: 'no-cors' })
  .then(response => response.json())
  .then(data => console.log(data));
Max Stanley
  • 81
  • 10
  • I still get the same error: TobuyList.js:31 Uncaught (in promise) SyntaxError: Unexpected end of input at TobuyList.js:31 – semicolon Jul 12 '20 at 16:49
  • This could potentially be an issue with CORS, https://stackoverflow.com/questions/45696999/fetch-unexpected-end-of-input , if CORS is not necessary try removing the option and see if that works. – Max Stanley Jul 12 '20 at 16:53