On this page
HTTP Module
The built-in http module creates servers and makes HTTP requests without external dependencies.
Creating a Server
import http from 'http';
const server = http.createServer((req, res) => {
const { method, url } = req;
if (method === 'GET' && url === '/') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Welcome!');
} else if (method === 'GET' && url === '/api/users') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify([{ id: 1, name: 'Alice' }]));
} else {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Not Found' }));
}
});
server.listen(3000, () => console.log('Server on port 3000'));
Parsing Request Body
function parseBody(req) {
return new Promise((resolve, reject) => {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
try {
resolve(body ? JSON.parse(body) : {});
} catch (err) {
reject(err);
}
});
req.on('error', reject);
});
}
server.on('request', async (req, res) => {
if (req.method === 'POST' && req.url === '/api/users') {
try {
const user = await parseBody(req);
res.writeHead(201, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ id: Date.now(), ...user }));
} catch {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid JSON' }));
}
}
});
Making HTTP Requests
import http from 'http';
const options = {
hostname: 'api.example.com',
port: 80,
path: '/users/1',
method: 'GET',
headers: { 'Accept': 'application/json' }
};
const req = http.request(options, (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => console.log(JSON.parse(data)));
});
req.on('error', (err) => console.error(err));
req.end();
Using fetch in Node.js (18+)
Node.js 18+ includes the global fetch API:
const response = await fetch('https://api.example.com/users');
const users = await response.json();
console.log(users);
Status Codes Reference
| Code | Meaning |
|---|---|
| 200 | OK |
| 201 | Created |
| 400 | Bad Request |
| 401 | Unauthorized |
| 404 | Not Found |
| 500 | Internal Server Error |
HTTPS
import https from 'https';
import fs from 'fs';
const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
https.createServer(options, (req, res) => {
res.end('Secure connection');
}).listen(443);
For production APIs, use Express (next chapter) instead of raw http — it simplifies routing, middleware, and error handling.