fetch in Node in JavaScript
The same fetch as the browser, with Node's error shapes.
async function getJSON(url) {
const response = await fetch(url, {
headers: { Accept: "application/json" },
signal: AbortSignal.timeout(5000),
});
if (!response.ok) {
throw new Error(`${response.status} ${response.statusText}`);
}
return response.json();
}
async function post(url, body) {
const response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
return { status: response.status, ok: response.ok };
}
console.log(typeof getJSON, typeof post, typeof fetch);
How it works
- A 404 is a successful fetch with
okfalse. - Only a transport failure rejects.
AbortSignal.timeoutis how you bound it.
Keywords and builtins used here
JSONasyncawaitconstfunctionifreturnthrow
The run, in numbers
- Lines
- 21
- Characters to type
- 534
- Tokens
- 143
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 78 seconds.
Step 2 of 3 in Network, step 13 of 18 in Node.js.