HTTP headers carry metadata about requests and responses. Use res.setHeader() or res.writeHead() to set response headers. Common headers include Content-Type, Authorization, and CORS headers.
Always send the correct HTTP status code: 200 OK, 201 Created, 400 Bad Request, 401 Unauthorized, 404 Not Found, 500 Internal Server Error.
Example
const http = require('http');
const server = http.createServer((req, res) => {
// Read request headers:
const contentType = req.headers['content-type'];
const authHeader = req.headers['authorization'];
console.log('Content-Type:', contentType);
console.log('Authorization:', authHeader);
// Set individual response headers:
res.setHeader('X-Powered-By', 'Node.js');
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Cache-Control', 'no-store');
// writeHead sets status + headers at once:
res.writeHead(200, {
'Content-Type': 'application/json',
'X-Request-ID': '12345',
});
// Status code reference:
// 200 OK — success
// 201 Created — resource created
// 204 No Content — success, no body
// 301 Moved Permanently — redirect
// 400 Bad Request — client error
// 401 Unauthorized — not authenticated
// 403 Forbidden — not authorized
// 404 Not Found — resource missing
// 500 Internal Server Error — server crash
res.end(JSON.stringify({ status: 'ok' }));
});
server.listen(3000);