Hi, I’m struggling to get a function that fetches JSON data from an API endpoint at https://api.postcodes.io using {fetch}. Their documentation requires a JSON object to be passed with the POST request. Below is an example of that object from https://api.postcodes.io documentation.
{
"postcodes" : ["OX49 5NU", "M32 0JG", "NE30 1DP"]
}
My function is as follows, and is stored in the backend (per CORS requirement):
import { fetch } from 'wix-fetch';
export function callAPI() {
return fetch("https://api.postcodes.io/postcodes", {
"method": "post",
"headers": {
"Content-Type": "application/json"
},
"body": {
"postcodes": ["EH14 4AS", "PE28 4UX"]
},
})
.then((httpResponse) => {
if (httpResponse.ok) {
return httpResponse.json();
} else {
console.log(httpResponse);
return Promise.reject("callAPI failed");
}
})
.then((json) => console.log(json.result))
.catch(err => console.log(err));
}
httpResponse.status is 400, i.e. bad request. I’m not overly familiar with constructing JSON objects or POST requests. I’ve made life difficult for myself because I had GET request working fine for a single postcode!
Any help is greatly appreciated!