Request & Response

Read details from req and build the reply on res.

Syntaxres.writeHead(200, headers); res.end(body);

The two objects passed to your handler are the request and the response.

The request (req)

  • req.method — GET, POST, etc.
  • req.url — the path requested.
  • req.headers — the request headers.

The response (res)

  • res.statusCode — set the status.
  • res.setHeader() — set a header.
  • res.write() / res.end() — send the body.

Example

Example · javascript
const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/html' });
  res.write('<h1>Home</h1>');
  res.write(`<p>You asked for: ${req.url}</p>`);
  res.end();
});

server.listen(3000);

When to use it

  • An API gateway reads `req.headers['authorization']` to validate a Bearer token before proxying the request to a downstream service.
  • A file-upload handler reads `req` as a stream to write incoming binary data directly to disk without buffering the whole body in memory.
  • A REST API sets `res.statusCode`, adds JSON content-type headers, and calls `res.end(json)` to send a structured error response.

More examples

Read request headers and body

Collects the full request body from the readable `req` stream by listening for `data` and `end` events.

Example · js
const http = require('http');

http.createServer((req, res) => {
  let body = '';
  req.on('data',  chunk => body += chunk);
  req.on('end',   () => {
    console.log('Headers:', req.headers);
    console.log('Body:',    body);
    res.end('Received');
  });
}).listen(3000);

Write response headers and body

Sets a 201 Created status, a Location header, and sends a JSON body -- typical of a REST POST response.

Example · js
const http = require('http');

http.createServer((req, res) => {
  res.statusCode = 201;
  res.setHeader('Content-Type', 'application/json');
  res.setHeader('Location', '/items/42');
  res.end(JSON.stringify({ id: 42, created: true }));
}).listen(3000);

Make an outgoing HTTP request

Uses `https.get` to make an outgoing GET request and accumulate the response body from its readable stream.

Example · js
const https = require('https');

https.get('https://api.github.com/zen', {
  headers: { 'User-Agent': 'node-demo' },
}, (res) => {
  let data = '';
  res.on('data', c => data += c);
  res.on('end',  () => console.log(data));
});

Discussion

  • Be the first to comment on this lesson.
Request & Response — Node.js | SoundsCode