← Back to Node.js Course | Chapter 8: Working with APIs | Lesson 6 of 7

Axios/fetch in Node

Node can call other APIs using the built-in fetch, or libraries like Axios.

In this page:

  1. Axios/fetch in Node
Syntax
javascript
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

javascript
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
  1. Assuming fetch rejects on 404
  2. Forgetting to await json()
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.