Hello i want to get response header after fetch POST request. I tried to debug to see what inside response with console.log(response). I can get response bodies from responseData but i have no idea how to get the header. I want to get both header and the body. Please help. thanks:)
Here's the example what i've done:
fetch(URL_REGISTER, {
method: 'POST',
body: formData
})
.then((response) => response.json())
.then((responseData) => {
if(responseData.success == 1){
this.setState({
message1: responseData.msg,
});
}
else{
this.setState({
message1: responseData.msg,
});
}
})
.done();
},
you can do like this
fetchData() {
var URL_REGISTER = 'https://www.example.com';
fetch(URL_REGISTER, {method: 'POST',body: formData})
.then(
function(response) {
console.log(response.headers.get('Content-Type'));
console.log(response.headers.get('Date'));
console.log(response.status);
console.log(response.statusText);
console.log(response.type);
console.log(response.url);
if (response.status !== 200) {
console.log('Status Code: ' + response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error', err);
});
}
Read More about fetch: Introduction to fetch()
You can take the headers from response.headers
fetch(URL_REGISTER, {
method: 'POST',
body: formData
})
.then((response) => {
console.log(response.headers); //Returns Headers{} object
}
You should return response.json() like return response.json();
Related
So I am making a request to an API endpoint. When I print JSONBody which is the variable data passed to POSTRequest(), I get the JSON I created printed to the log, however when I then try and JSON.Stringify() it, I get returned an empty object?
Was just wondering what I am doing wrong and how to fix it :)
getFileData()
const getFileData = () => {
var data = {}
// DO SOME STUFF HERE TO data
POSTRequest(data);
}
POSTRequest()
const POSTRequest = async (JSONBody) => {
console.log(JSONBody)
console.log(JSON.stringify(JSONBody))
try {
const response = await fetch(API_ENDPOINT, {
method: 'POST',
body: JSON.stringify(JSONBody),
headers: { 'Content-Type': 'application/json' }
});
response.json()
.then(function (res) {
Promise.resolve(res)
.then(function (finalData) {
console.log(finalData);
props.setData(finalData);
});
});
} catch (error) {
console.log(error);
}
}
You're not waiting for the response from the fetch call correctly, try this:
const POSTRequest = async (JSONBody) => {
console.log(JSONBody)
console.log(JSON.stringify(JSONBody))
await fetch(API_ENDPOINT, {
method: 'POST',
body: JSON.stringify(JSONBody),
headers: { 'Content-Type': 'application/json' }
}).then((response) => {
console.log(response);
props.setData(response);
}).catch((error) => {
console.log('POSTRequest error: ' + error)
})
});
I have a fetch call to an API. I need both status and the HTML response.
fetch('api/post/email', {
method: 'POST',
body: JSON.stringify(data)
}).then((response) => {
console.log(response.text());
console.log(response.body);
if (response.status == 200) {
console.log(response.status);
} else {
console.log(response.status);
}
});
I get this results from above:
Promise {<pending>}
ReadableStream {locked: true}
404
The last one status is fine, but...
What is the easiest way to get the body or the HTML results from the API with fetch?
fetch('api/post/email', {
method: 'POST',
body: JSON.stringify(data)
}).then((response) => {
response.text().then(re => {
console.log(re);
});
console.log(response.body);
if (response.status == 200) {
console.log(response.status);
} else {
console.log(response.status);
}
});
Response.text() returns a promise so you have to handle it like it's suposed to be handled. (passing in a callback) after that you can log it , inside the callback.
The simples way I can think of is using async/await.
Note: response.text() returns a promise that resolves to the text.
fetch('api/post/email', {
method: 'POST',
body: JSON.stringify(data)
}).then(async (response) => {
const text = await response.text();
if (response.status == 200) {
console.log(response.status);
} else {
console.log(response.status);
}
console.log(text);
});
I am using the fetch API with a REST API, and i want to handle certain errors globally, errors like 500, 503 ... I tried doing something like this
function(url, method, data) {
return fetch(url, {
method: method || "GET",
body: JSON.stringify(data),
mode: "cors",
headers: {
"Content-Type": "application/json; charset=utf-8"
}
}).then(response => {
if (response.ok && response.status < 500) console.log("ouch");;
return response;
});
but it doesn't seem to be working. how do i catch 500, 503 ... in the fetch api?
Try this approach in this way you can handle all possible errors at one place and you also can generate custom response to return e.g if your all requests return JSON data then you can convert response to JSON before returning it.
function secureFetch(url, method, data) {
return new Promise((resolve, reject) => {
fetch(url, {
method: method || "GET",
body: JSON.stringify(data),
mode: "cors",
headers: {
"Content-Type": "application/json; charset=utf-8"
}
}).then(response => {
// response only can be ok in range of 2XX
if (response.ok) {
// you can call response.json() here too if you want to return json
resolve(response);
} else {
//handle errors in the way you want to
switch (response.status) {
case 404:
console.log('Object not found');
break;
case 500:
console.log('Internal server error');
break;
default:
console.log('Some error occured');
break;
}
//here you also can thorow custom error too
reject(response);
}
})
.catch(error => {
//it will be invoked mostly for network errors
//do what ever you want to do with error here
console.log(error);
reject(error);
});
});
}
secureFetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.log(error));
secureFetch('https://jsonplaceholder.typicode.com/posts/100000000')
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.log(error));
Here you can handle with promise something like this:
function status(response) {
/*You can handle status here.*/
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response)
} else {
return Promise.reject(new Error(response.statusText))
}
}
function json(response) {
return response.json()
}
function makeCall(url, method, data) {
return fetch(url, {
method: method || "GET",
body: JSON.stringify(data),
mode: "cors",
headers: {
"Content-Type": "application/json; charset=utf-8"
}
})
.then(status)
.then(json)
.then(function(data) {
console.log('Request succeeded with JSON response', data);
}).catch(function(error) {
console.log('Request failed', error);
});
}
var url = 'http://localhost:4200/profile';
var data = {username: 'example'};
makeCall(url, 'POST', data);
I have the following function which came from the mern.io stack.
export default function callApi(endpoint, method = 'get', body) {
return fetch(`${API_URL}/${endpoint}`, {
headers: { 'content-type': 'application/json' },
method,
body: JSON.stringify(body),
})
.then(response => response.json().then(json => ({ json, response })))
.then(({ json, response }) => {
if (!response.ok) {
return Promise.reject(json);
}
return json;
})
.then(
response => response,
error => error
);
}
I call the function the following way
callApi('auth/register', 'post', {
username,
password,
}).then(function(res) {
// do stuff
});
The response will either be a 201 or a 422. How can handle the 422 the proper way? A 422 would occur if a username already exists.
Do I put all the logic in the first then such as the following:
callApi('auth/register', 'post', {
username,
password,
}).then(function(res) {
if (res.error) {
} else {
}
});
Assuming callApi returns a Promise object:
callApi('auth/register', 'post', {
username,
password,
}).then(function(res) {
// res
}).catch(function(err) {
// handle err
});
For more information: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
I'm using the native fetch library as specified here. It seems that whenever a response other than a 200 OK is returned it throws an exception with the string response Uncaught (in promise) TypeError: Failed to fetch.
Was there a way to catch and branch on specific HTTP response codes and still view the response data? For example a 401 response?
I have attached my request code I am using as a wrapper for fetch.
static request(url, data) {
let headers = {
"Authorization": window.localStorage.getItem("Authorization"),
"Content-Type": "application/json"
};
let options = {
method: "GET",
headers: headers,
mode: "no-cors",
cache: "no-cache",
};
if (data) {
options = {
method: "POST",
headers: headers,
mode: "no-cors",
cache: "no-cache",
body: JSON.stringify(data)
}
}
return new Promise(async (resolve, reject) => {
try {
let response = await fetch(url, options);
let jsonResponse = await response.json();
return resolve(jsonResponse);
} catch (error) {
// hashHistory.push("/login");
return reject(error);
}
})
}
"An accurate check for a successful fetch() would include checking that the promise resolved, then checking that the Response.ok property has a value of true. The code would look something like this (https://developer.mozilla.org/pt-BR/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful):
fetch('flowers.jpg').then(function(response) {
if(response.ok) {
response.blob().then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});
} else {
console.log('Network response was not ok.');
}
})
.catch(function(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
});
"
You can check Response Headers .status property, .text() to read Response. If Response is expected to be read more than once, you can use .clone()
let request = fetch("/path/to/resource");
request
.then(response => {
const status = response.headers.get("status");
console.log(status);
if (status == 401) {
// read 401 response
response.text().then(res = > console.log(res));
return "404.html"
}
if (status == 200) {
return "200.html"
}
})
.then(result => console.log(result))
.catch(err => // handle error);