-1

I am trying to make a request to an api with node-fetch. I've followed the documentation but it doesn't seem to do anything.

I have modified the options and it seems that nothing has changed. Headers and body are ignored.

When I test with postman and see the request in the console, it is empty and returns nothing.

This is the code :

let myheaders ={
    'Content-type': 'application/json',
}

let raw = {
     "user": "user",
     "pw": "pw"
};

let defaultOptions = {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    //mode: 'cors', // no-cors, *cors, same-origin
    //credentials: 'include', // include, *same-origin, omit
    headers: myheaders,
    body: JSON.stringify(raw) // body data type must match "Content-Type" header
  }

   const response = await fetch("url",defaultOptions);
   const responseText = await response.text();
   console.log(responseText);
   res.send(responseText);

 //.then(response => response.text());
 //.then(result => console.log(result));
 //.catch(error => console.log('error', error));

 //res.json(response);

The postman console displays :

Request headers
   -Postman Token : 'token'
Request body
   -Ø

I have tried everything that has been suggested in posts similar to this one and cannot find the solution.

thanks

Mat
  • 33
  • 1
  • 7
  • You have used both async/await and promise chains. Use any one method. – Rahul K May 03 '22 at 05:45
  • Thanks for the comment! I removed the await but the request is still empty. – Mat May 03 '22 at 05:47
  • 1
    That's because the promise chains don't return any value. All the values are available only inside the callbacks, try using the answer posted below. – Rahul K May 03 '22 at 05:52
  • `.then(result => console.log(result))` resolves the promise chain with the return value of `console.log()` which is `undefined`. – Phil May 03 '22 at 06:00

1 Answers1

1

As per my comment, try using like this as mentioned in the docs.

const response = await fetch("url", defaultOptions);
const responseText = await response.text();
Rahul K
  • 73
  • 1
  • 8
  • If I do a console.log(responseText), it only shows an empty result. The request is still empty in postman – Mat May 03 '22 at 05:55
  • Please check your input parameters then, I've used the way suggested in docs. – Rahul K May 03 '22 at 05:58
  • I don't understand how even the body is not shown in the postman request. If you check the headers in the console it only shows the postman-token that is generated automatically. – Mat May 03 '22 at 06:02
  • Maybe try `res.send(responseText)` as its no longer a json, forgot to catch it. – Rahul K May 03 '22 at 06:04
  • Still the same. There is no error in postman or in the server console. – Mat May 03 '22 at 06:09
  • Can you provide a screenshot of your postman request page – Rahul K May 03 '22 at 06:11
  • The question now shows exactly the two empty fields that I see in the console. Headers and body – Mat May 03 '22 at 06:18