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

Node में Axios/fetch

Node built-in fetch, या Axios जैसी libraries इस्तेमाल करके दूसरे APIs call कर सकता है।
Syntax
javascript
const response = await fetch(url);
const data = await response.json();

Node में Axios/fetch

Node 18 और बाद वाले में fetch API शामिल है। यह एक Response का एक promise return करता है जिसके json और text methods भी promises return करते हैं। fetch HTTP error statuses पर reject नहीं होता, इसलिए response.ok check करें।

Axios interceptors और automatic JSON handling जैसी conveniences add करता है।

Note: parse करने से पहले response.ok check करें।

उदाहरण: 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/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह मान लेना कि fetch 404 पर reject होता है
  2. json() await करना भूल जाना
  3. timeouts set न करना
चैप्टर सारांश
  • Node 18 से fetch built in है
  • response.ok check करें
  • json() एक promise return करता है
  • Axios conveniences add करता है
🔒

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.