I am making a fetch api POST request to a url. When I print the data to my console, it says undefined. Here is my code:
function arCall(url = '', data = {}) {
fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Basic ' btoa('<my Username>:<my Password>'),
},
body: JSON.stringify(data)
})
.then((res) => console.log(res))
.then(data => console.log(data))
}
arCall('<my URL>', { id: 111 });
In the inspect tab on chrome, this is what the output looks like:
This is the Response object:
Could the reason for the undefined data be that I am getting a 403 forbidden error?
CodePudding user response:
.then((res) => console.log(res)) .then(data => console.log(data))
The value passed to a then
callback is the resolved value of the promise returned from the previous step in the chain.
The return value of console.log
is undefined
.
Therefore .then((res) => console.log(res))
returns a promise that resolves as undefined
.
Therefore the value passed to data
is undefined
.
In the general case, you'll want to call one of the functions that processes the body of the response object and returns a promise that resolves as its value.
.then((res) => {
console.log(res);
return res.text();
})
.then(data => console.log(data))
In this specific case, since you are getting a 403 Forbidden response, that's unlikely to be useful and you should change the request so you get a more useful response.