- Spec files
npm-express
Describes: pkg:npm/express@4.21.x
- Description
- Fast, unopinionated, minimalist web framework for Node.js
- Author
- tessl
- Last updated
request.md docs/
1# Request Processing23Enhanced request object with Express-specific properties and methods for handling incoming HTTP requests, accessing headers, parameters, and parsing request data.45## Capabilities67### Request Properties89Access request information including URL components, headers, and parsed data.1011```javascript { .api }12/**13* Express request object extends Node.js IncomingMessage14*/15interface Request {16/** Reference to Express application instance */17app: Application;18/** Base URL path (mount path for sub-apps) */19baseUrl: string;20/** Request body (populated by body parsing middleware) */21body: any;22/** Parsed cookies from Cookie header */23cookies: { [key: string]: string };24/** Signed cookies when cookie-parser used with secret */25signedCookies: { [key: string]: string };26/** Check if request is fresh (based on Last-Modified/ETag) */27fresh: boolean;28/** Request hostname (Host header without port) */29hostname: string;30/** Remote IP address */31ip: string;32/** Array of IP addresses (when trust proxy enabled) */33ips: string[];34/** HTTP method (GET, POST, etc.) */35method: string;36/** Original URL as received by the server */37originalUrl: string;38/** Route parameters from URL path */39params: { [key: string]: string };40/** Request path portion of URL */41path: string;42/** Request protocol (http or https) */43protocol: string;44/** Parsed query string parameters */45query: { [key: string]: any };46/** Raw query string */47rawQuery: string;48/** Currently matched route object */49route: Route;50/** True if connection is secure (HTTPS) */51secure: boolean;52/** True if request is stale (opposite of fresh) */53stale: boolean;54/** Array of subdomains */55subdomains: string[];56/** True if request is XMLHttpRequest (Ajax) */57xhr: boolean;58}59```6061**Usage Examples:**6263```javascript64app.get('/info', (req, res) => {65const requestInfo = {66method: req.method, // 'GET'67path: req.path, // '/info'68hostname: req.hostname, // 'localhost'69protocol: req.protocol, // 'http'70secure: req.secure, // false71ip: req.ip, // '127.0.0.1'72xhr: req.xhr, // false73fresh: req.fresh, // true/false74stale: req.stale // true/false75};7677res.json(requestInfo);78});7980// Access route parameters81app.get('/users/:id/posts/:postId', (req, res) => {82const { id, postId } = req.params;83res.json({ userId: id, postId });84});8586// Access query parameters87app.get('/search', (req, res) => {88const { q, limit, offset } = req.query;89res.json({ query: q, limit, offset });90});9192// Access request body (requires body parser)93app.post('/users', (req, res) => {94const { name, email } = req.body;95res.json({ name, email });96});97```9899### Header Access100101Retrieve request headers and perform content negotiation.102103```javascript { .api }104/**105* Get request header value (case-insensitive)106* @param {string} field - Header field name107* @returns {string | undefined} Header value or undefined108*/109req.get(field: string): string | undefined;110111/**112* Alias for req.get()113* @param {string} field - Header field name114* @returns {string | undefined} Header value or undefined115*/116req.header(field: string): string | undefined;117```118119**Usage Examples:**120121```javascript122app.get('/headers', (req, res) => {123const headers = {124userAgent: req.get('User-Agent'),125contentType: req.get('Content-Type'),126authorization: req.header('authorization'),127accept: req.get('Accept'),128host: req.get('Host')129};130131res.json(headers);132});133134// Custom header processing135app.use((req, res, next) => {136const apiKey = req.get('X-API-Key');137const version = req.get('X-API-Version') || 'v1';138139req.apiKey = apiKey;140req.apiVersion = version;141next();142});143```144145### Content Negotiation146147Determine client preferences for response format based on Accept headers.148149```javascript { .api }150/**151* Check if request accepts specified content types152* @param {string | string[]} types - MIME types to check153* @returns {string | false} Best matching type or false154*/155req.accepts(types?: string | string[]): string | false;156157/**158* Check if request accepts specified charsets159* @param {string | string[]} charsets - Character sets to check160* @returns {string | false} Best matching charset or false161*/162req.acceptsCharsets(charsets?: string | string[]): string | false;163164/**165* Check if request accepts specified encodings166* @param {string | string[]} encodings - Content encodings to check167* @returns {string | false} Best matching encoding or false168*/169req.acceptsEncodings(encodings?: string | string[]): string | false;170171/**172* Check if request accepts specified languages173* @param {string | string[]} languages - Languages to check174* @returns {string | false} Best matching language or false175*/176req.acceptsLanguages(languages?: string | string[]): string | false;177```178179**Usage Examples:**180181```javascript182app.get('/data', (req, res) => {183const accepts = req.accepts(['json', 'xml', 'html']);184185switch (accepts) {186case 'json':187res.json({ message: 'JSON response' });188break;189case 'xml':190res.type('xml').send('<message>XML response</message>');191break;192case 'html':193res.send('<h1>HTML response</h1>');194break;195default:196res.status(406).send('Not Acceptable');197}198});199200// Language negotiation201app.get('/greeting', (req, res) => {202const lang = req.acceptsLanguages(['en', 'es', 'fr']);203204const greetings = {205en: 'Hello',206es: 'Hola',207fr: 'Bonjour'208};209210res.json({211greeting: greetings[lang] || greetings.en,212language: lang || 'en'213});214});215216// Encoding negotiation217app.get('/large-data', (req, res) => {218const encoding = req.acceptsEncodings(['gzip', 'deflate']);219220if (encoding) {221// Compress response based on accepted encoding222res.set('Content-Encoding', encoding);223}224225res.json({ data: 'large dataset', compressed: !!encoding });226});227```228229### Content Type Checking230231Check the content type of incoming requests.232233```javascript { .api }234/**235* Check if request content type matches specified types236* @param {string | string[]} types - Content types to check against237* @returns {string | false} Matching type or false238*/239req.is(types: string | string[]): string | false;240```241242**Usage Examples:**243244```javascript245app.post('/upload', (req, res) => {246if (req.is('application/json')) {247// Handle JSON upload248res.json({ type: 'json', body: req.body });249} else if (req.is('multipart/form-data')) {250// Handle file upload251res.json({ type: 'multipart' });252} else if (req.is('text/*')) {253// Handle any text content254res.json({ type: 'text' });255} else {256res.status(415).json({ error: 'Unsupported Media Type' });257}258});259260// Multiple content type check261app.post('/api/data', (req, res) => {262const contentType = req.is(['json', 'urlencoded', 'text']);263264if (!contentType) {265return res.status(415).json({266error: 'Content-Type must be JSON, form data, or text'267});268}269270res.json({ acceptedType: contentType });271});272```273274### Range Header Processing275276Handle Range requests for partial content (useful for file serving and streaming).277278```javascript { .api }279/**280* Parse Range header for partial content requests281* @param {number} size - Total size of the resource282* @param {RangeOptions} [options] - Range parsing options283* @returns {RangeResult | undefined} Parsed range or undefined284*/285req.range(size: number, options?: RangeOptions): RangeResult | undefined;286287/**288* Range parsing options289*/290interface RangeOptions {291/** Combine overlapping ranges (default: false) */292combine?: boolean;293}294295/**296* Range parsing result297*/298interface RangeResult {299/** Range type (usually 'bytes') */300type: string;301/** Array of range specifications */302ranges: Array<{303start: number;304end: number;305}>;306}307```308309**Usage Examples:**310311```javascript312const fs = require('fs');313314app.get('/video/:id', (req, res) => {315const videoPath = `./videos/${req.params.id}.mp4`;316const stat = fs.statSync(videoPath);317const fileSize = stat.size;318319const range = req.range(fileSize);320321if (range) {322// Handle range request for video streaming323const { start, end } = range.ranges[0];324const chunkSize = (end - start) + 1;325const stream = fs.createReadStream(videoPath, { start, end });326327res.status(206); // Partial Content328res.set({329'Content-Range': `bytes ${start}-${end}/${fileSize}`,330'Accept-Ranges': 'bytes',331'Content-Length': chunkSize,332'Content-Type': 'video/mp4'333});334335stream.pipe(res);336} else {337// Send entire file338res.set({339'Content-Length': fileSize,340'Content-Type': 'video/mp4'341});342fs.createReadStream(videoPath).pipe(res);343}344});345```346347### Parameter Access (Deprecated)348349Legacy parameter access method (deprecated in favor of specific property access).350351```javascript { .api }352/**353* Get parameter value from params, body, or query (deprecated)354* @param {string} name - Parameter name355* @param {any} [defaultValue] - Default value if not found356* @returns {any} Parameter value or default357* @deprecated Use req.params, req.body, or req.query directly358*/359req.param(name: string, defaultValue?: any): any;360```361362**Usage Examples (Not Recommended):**363364```javascript365// Deprecated - don't use366app.get('/old-style/:id', (req, res) => {367const id = req.param('id'); // Gets from params368const name = req.param('name'); // Gets from query/body369370res.json({ id, name });371});372373// Preferred modern approach374app.get('/modern/:id', (req, res) => {375const { id } = req.params;376const { name } = req.query;377378res.json({ id, name });379});380```381382## Request Object Extensions383384Custom properties can be added to the request object by middleware for sharing data between middleware functions.385386```javascript387// Type extension for custom properties388declare global {389namespace Express {390interface Request {391user?: User;392apiKey?: string;393apiVersion?: string;394requestId?: string;395}396}397}398399// Middleware adding custom properties400app.use((req, res, next) => {401req.requestId = generateRequestId();402next();403});404405app.use('/api', (req, res, next) => {406req.apiVersion = req.get('X-API-Version') || 'v1';407next();408});409```