The Request and Response Objects
9 min read
The Request and Response Objects
The req object extends Node's IncomingMessage and gives you everything about the incoming HTTP request. The res object extends ServerResponse and provides methods for building your reply.
Commonly Used Request Properties
req.method— HTTP verb ("GET", "POST", ...)req.url— raw request URL including query stringreq.path— pathname without query stringreq.headers— all request headers as an objectreq.body— parsed request body (requires middleware)req.params— named URL segmentsreq.query— parsed query string parametersreq.cookies— cookies (requires cookie-parser middleware)req.ip— client IP address
Commonly Used Response Methods
res.send(body)— send a response (string, Buffer, or object)res.json(obj)— send a JSON response with Content-Type headerres.status(code)— set the HTTP status code (chainable)res.set(name, value)— set a response headerres.redirect(url)— send a 302 redirectres.sendFile(path)— stream a file to the clientres.end()— close the connection without a body
Always end the request-response cycle by calling exactly one of res.send(), res.json(), res.end(), res.redirect(), or res.sendFile(). Calling more than one will throw a headers-already-sent error.
Ready to test yourself?
Practice Express— quiz & coding exercises