Call other servers from Node. Use the built-in fetch to GET and POST data, handle JSON responses and errors, and reach for axios when you want extra conveniences.
Why: fetch sends an HTTP request to another server and returns a Promise. It is built into modern Node (no install needed) and works the same as fetch in the browser. Call .json() on the response to parse the JSON body.
// app.js
const res = await fetch('https://api.github.com/users/torvalds')
const user = await res.json()
console.log(user.name, user.public_repos)Why: fetch only rejects on network failures — a 404 or 500 still "succeeds" as far as the Promise is concerned. You must check res.ok (true for 200-299) yourself and throw if the server reported a problem.
// app.js
const res = await fetch('https://api.example.com/data')
if (!res.ok) {
throw new Error('Request failed: ' + res.status)
}
const data = await res.json()Why: to create or update something on a server you send a POST with a body. Set the method, tell the server the body is JSON with a header, and stringify your object.
// app.js
const res = await fetch('https://api.example.com/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Ada', role: 'admin' }),
})
const created = await res.json()Why: axios is a widely used package that wraps HTTP calls. It parses JSON for you, throws automatically on error statuses, and supports timeouts and interceptors — conveniences fetch leaves to you.
$ pnpm add axios// app.js
import axios from 'axios'
// axios parses JSON and throws on 4xx/5xx automatically
const { data } = await axios.get('https://api.github.com/users/torvalds')
console.log(data.name)
await axios.post('https://api.example.com/users', { name: 'Ada' })