- Spec files
npm-express
Describes: pkg:npm/express@5.1.x
- Description
- Fast, unopinionated, minimalist web framework for Node.js
- Author
- tessl
- Last updated
request.md docs/
1# Request Processing23Request object enhancements providing access to headers, query parameters, content negotiation, and request metadata analysis.45## Capabilities67### Header Access89Retrieve request headers with case-insensitive lookup.1011```javascript { .api }12/**13* Get request header field value (case-insensitive)14* @param {string} name - Header field name15* @returns {string|undefined} Header value or undefined if not found16*/17get(name: string): string | undefined;1819/**20* Alias for get() method21* @param {string} name - Header field name22* @returns {string|undefined} Header value or undefined if not found23*/24header(name: string): string | undefined;25```2627**Usage Examples:**2829```javascript30app.get('/api/data', (req, res) => {31// Get headers32const contentType = req.get('Content-Type');33const userAgent = req.header('User-Agent');34const authorization = req.get('authorization'); // Case insensitive3536console.log('Content-Type:', contentType);37console.log('User-Agent:', userAgent);3839res.json({ received: true });40});41```4243### Content Negotiation4445Determine the best response format based on client Accept headers.4647```javascript { .api }48/**49* Check if given types are acceptable based on Accept header50* @param {string|string[]} types - MIME type(s) to check51* @returns {string|false} Best match or false if none acceptable52*/53accepts(types: string | string[]): string | false;5455/**56* Check if given encodings are acceptable based on Accept-Encoding header57* @param {string|string[]} encodings - Encoding(s) to check58* @returns {string|false} Best match or false if none acceptable59*/60acceptsEncodings(encodings: string | string[]): string | false;6162/**63* Check if given charsets are acceptable based on Accept-Charset header64* @param {string|string[]} charsets - Charset(s) to check65* @returns {string|false} Best match or false if none acceptable66*/67acceptsCharsets(charsets: string | string[]): string | false;6869/**70* Check if given languages are acceptable based on Accept-Language header71* @param {string|string[]} langs - Language(s) to check72* @returns {string|false} Best match or false if none acceptable73*/74acceptsLanguages(langs: string | string[]): string | false;75```7677**Usage Examples:**7879```javascript80app.get('/api/data', (req, res) => {81// Content type negotiation82const format = req.accepts(['json', 'xml', 'html']);8384switch (format) {85case 'json':86res.json({ data: 'JSON response' });87break;88case 'xml':89res.type('xml').send('<data>XML response</data>');90break;91case 'html':92res.send('<h1>HTML response</h1>');93break;94default:95res.status(406).send('Not Acceptable');96}97});9899app.get('/compressed', (req, res) => {100// Check encoding support101if (req.acceptsEncodings('gzip')) {102// Send compressed response103res.set('Content-Encoding', 'gzip');104// ... compress and send105} else {106// Send uncompressed107}108});109```110111### Request Analysis112113Analyze request content and characteristics.114115```javascript { .api }116/**117* Check if request contains given Content-Type118* @param {string|string[]} types - Content type(s) to check119* @returns {string|false} Matching type or false if no match120*/121is(types: string | string[]): string | false;122123/**124* Parse Range header field125* @param {number} size - Total size of resource126* @param {object} options - Parsing options (optional)127* @returns {object|number} Parsed ranges or -1 if malformed, -2 if unsatisfiable128*/129range(size: number, options?: object): object | number;130```131132**Usage Examples:**133134```javascript135app.post('/upload', (req, res) => {136// Check content type137if (req.is('multipart/form-data')) {138// Handle file upload139} else if (req.is('application/json')) {140// Handle JSON data141} else {142res.status(415).send('Unsupported Media Type');143}144});145146app.get('/video/:id', (req, res) => {147const videoSize = getVideoSize(req.params.id);148149// Handle range requests for video streaming150const ranges = req.range(videoSize);151if (ranges && ranges !== -1 && ranges !== -2) {152// Send partial content153res.status(206);154// ... send range155} else {156// Send full video157res.status(200);158// ... send complete file159}160});161```162163### Request Properties164165Access various request metadata and parsed data.166167```javascript { .api }168/**169* Parsed query string parameters170*/171query: { [key: string]: any };172173/**174* Route parameters from URL path175*/176params: { [key: string]: string };177178/**179* Request body (populated by body-parser middleware)180*/181body: any;182183/**184* Request protocol ('http' or 'https')185*/186protocol: string;187188/**189* True if protocol is https190*/191secure: boolean;192193/**194* Remote IP address (respects trust proxy setting)195*/196ip: string;197198/**199* Array of IP addresses when using proxy (trust proxy must be enabled)200*/201ips: string[];202203/**204* Array of subdomains205*/206subdomains: string[];207208/**209* Request URL pathname210*/211path: string;212213/**214* Original request URL (before any internal redirects)215*/216originalUrl: string;217218/**219* Base URL path on which app is mounted220*/221baseUrl: string;222223/**224* Host header field with port number225*/226host: string;227228/**229* Hostname without port number230*/231hostname: string;232233/**234* True if request is fresh (cache validation)235*/236fresh: boolean;237238/**239* True if request is stale (opposite of fresh)240*/241stale: boolean;242243/**244* True if X-Requested-With header indicates XMLHttpRequest245*/246xhr: boolean;247248/**249* Reference to the Express application instance250*/251app: Application;252253/**254* Reference to the response object for this request255*/256res: Response;257258/**259* Currently matched route object260*/261route: Route;262```263264**Usage Examples:**265266```javascript267app.get('/users/:id', (req, res) => {268// Route parameters269const userId = req.params.id;270271// Query parameters272const page = req.query.page || 1;273const limit = req.query.limit || 10;274275console.log(`Getting user ${userId}, page ${page}, limit ${limit}`);276277res.json({ userId, page, limit });278});279280app.post('/api/data', (req, res) => {281// Request body (requires body parser middleware)282const data = req.body;283284// Request metadata285console.log('Protocol:', req.protocol);286console.log('Secure:', req.secure);287console.log('IP:', req.ip);288console.log('Hostname:', req.hostname);289console.log('Path:', req.path);290291// Check if AJAX request292if (req.xhr) {293res.json({ message: 'AJAX request processed' });294} else {295res.redirect('/success');296}297});298299app.get('/cache-demo', (req, res) => {300if (req.fresh) {301// Client cache is fresh, send 304302res.status(304).end();303} else {304// Send fresh content305res.set('ETag', '"12345"');306res.send('Fresh content');307}308});309310// Subdomain routing311app.get('/', (req, res) => {312const subdomain = req.subdomains[0];313314if (subdomain === 'api') {315res.json({ message: 'API subdomain' });316} else if (subdomain === 'admin') {317res.send('Admin panel');318} else {319res.send('Main site');320}321});322```323324### Standard Node.js Properties325326The Express request object extends Node.js IncomingMessage, providing access to all standard HTTP request properties:327328```javascript { .api }329/**330* HTTP method (GET, POST, etc.)331*/332method: string;333334/**335* Request URL string336*/337url: string;338339/**340* HTTP headers object341*/342headers: { [key: string]: string | string[] };343344/**345* HTTP version346*/347httpVersion: string;348349/**350* Raw HTTP headers as array351*/352rawHeaders: string[];353```354355**Usage Examples:**356357```javascript358app.use((req, res, next) => {359// Log request details360console.log(`${req.method} ${req.url}`);361console.log('HTTP Version:', req.httpVersion);362console.log('Headers:', req.headers);363364next();365});366```