Skip to content

Instantly share code, notes, and snippets.

@BarryCarlyon
Last active November 1, 2022 14:45
Show Gist options
  • Save BarryCarlyon/b16e5e3771e4fb51d1818ef86b4fdfaa to your computer and use it in GitHub Desktop.
Save BarryCarlyon/b16e5e3771e4fb51d1818ef86b4fdfaa to your computer and use it in GitHub Desktop.
Javascript Fetch Example. That does JSON and preserves statuscode
let url = new URL('some url');
let params = [
[ 'param_1', 'value' ],
[ 'param_2', 'value' ]
];
url.search = new URLSearchParams(params).toString();
fetch(
url,
{
method: 'GET',
headers: {
'Accept': 'application/json'
}
}
)
.then(r => r.json().then(data => ({ status: r.status, headers: r.headers, body: data })))
.then((r) => {
if (r.status == 200) {
console.log('Got Data', r.body);
} else {
console.log('Error', r.status, r.body);
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment