Reputation: 574
I'm trying to make a request to api.postcodes.io/postcodes/:postcode/validate, to check if the postcode I have entered is a valid one. If I do this through the website I get a 200 response and a boolean result set to true when I enter a valid postcode and status: 200, result: false when I enter a random number. However, when trying to do this through my code I get no result. What could be the problem? I tried to parse the result using .json() but this just gave me an error.
This is my request:
const requestURL = 'https://api.postcodes.io/postcodes/' + addedPostcode + '/validate';
try {
console.log("enters try");
const response = yield fetch(requestURL, {
method: 'GET',
});
if(response.status === 200){
console.log("enters 200");
yield put({type: 'SHOW_ALERT', payload: {alertType: 'success', alertMessage: 'POST CODE VALID'}});
const updatedUser = yield response;
console.log(updatedUser);
} else{
console.log("enters 400");
const description = 'POST CODE INVALID';
yield put({type: 'SHOW_MODAL', payload: {type:'error', description}});
return;
}
} catch (e) {
console.log(e);
}
SOLUTION: Response needed to be parsed using .json(). Reason it was failing before is because my request url was missing the 'https://' part.
Upvotes: 0
Views: 16151
Reputation: 130
There are two status in this request and I think you're confused a bit.
First status is coming from fetch request. Second is coming from response body.
You can check these statuses that way:
const requestURL = 'https://api.postcodes.io/postcodes/SO152GB/validate';
const response = await fetch(requestURL, {
method: 'GET',
});
if(response.status === 200) {
// you can access to body with this way.
const body = await response.json();
if(body.status === 200) {
// your business
}
}
Upvotes: 0
Reputation: 2926
Try changing this line
if(response.status === 200){
to this
if(response.result && response.result === true){
Upvotes: 0
Reputation: 21
I think they alway return a status of 200. But if you enter a valid UK zip code they return
{
"status": 200,
"result": true
}
otherwise they return "result": false.
I've tested it with the following request url: api.postcodes.io/postcodes/SO152GB/validate
Upvotes: 1