Node में Axios/fetch
Node built-in fetch, या Axios जैसी libraries इस्तेमाल करके दूसरे APIs call कर सकता है।
In this page:
Syntax
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
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. #}
आम गलतियां
- यह मान लेना कि fetch 404 पर reject होता है
- json() await करना भूल जाना
- 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: