Axios/fetch in Node
Node can call other APIs using the built-in fetch, or libraries like Axios.
In this page:
Syntax
const response = await fetch(url);
const data = await response.json();
Axios/fetch in Node
Node 18 and later includes the fetch API. It returns a promise of a Response whose json and text methods also return promises. fetch does not reject on HTTP error statuses, so check response.ok.
Axios adds conveniences like interceptors and automatic JSON handling.
Note:
Check response.ok before parsing.
Example: Axios/fetch in Node
const http = require("http");
const server = http.createServer((req, res) => {
if (req.url === "/ok") { res.setHeader("Content-Type", "application/json"); return res.end('{"n":1}'); }
res.statusCode = 404; res.end("nope");
});
server.listen(0, async () => {
const base = "http://localhost:" + server.address().port;
const good = await fetch(base + "/ok");
console.log(good.ok, await good.json());
const bad = await fetch(base + "/missing");
console.log(bad.ok, bad.status);
server.close();
});
// Output:
// true { n: 1 }
// false 404
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Assuming fetch rejects on 404
- Forgetting to await json()
- Not setting timeouts
Chapter Summary
- fetch is built in from Node 18
- Check response.ok
- json() returns a promise
- Axios adds conveniences
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: