Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

javascript - API always returns 200 with no data in the response

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.

question from:https://stackoverflow.com/questions/65902597/api-always-returns-200-with-no-data-in-the-response

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...