- Spec files
npm-express
Describes: pkg:npm/express@5.1.x
- Description
- Fast, unopinionated, minimalist web framework for Node.js
- Author
- tessl
- Last updated
response.md docs/
1# Response Generation23Response object enhancements for sending various types of responses, setting headers, managing cookies, and handling redirects.45## Capabilities67### Response Sending89Send responses with automatic content-type detection and format handling.1011```javascript { .api }12/**13* Send response with automatic content-type detection14* @param {any} body - Response body (string, Buffer, object, array)15* @returns {Response} Response object for chaining16*/17send(body?: any): Response;1819/**20* Send JSON response21* @param {any} obj - Object to serialize as JSON22* @returns {Response} Response object for chaining23*/24json(obj: any): Response;2526/**27* Send JSON response with JSONP callback support28* @param {any} obj - Object to serialize as JSON29* @returns {Response} Response object for chaining30*/31jsonp(obj: any): Response;3233/**34* Send status code with default message as response body35* @param {number} statusCode - HTTP status code36* @returns {Response} Response object for chaining37*/38sendStatus(statusCode: number): Response;39```4041**Usage Examples:**4243```javascript44app.get('/', (req, res) => {45// Send string response46res.send('Hello World!');47});4849app.get('/api/users', (req, res) => {50// Send JSON response51res.json({52users: [53{ id: 1, name: 'Alice' },54{ id: 2, name: 'Bob' }55]56});57});5859app.get('/jsonp-data', (req, res) => {60// Send JSONP response (checks for callback query parameter)61res.jsonp({ message: 'JSONP response' });62// If ?callback=myFunc, sends: myFunc({"message":"JSONP response"});63});6465app.delete('/users/:id', (req, res) => {66// Send status with default message67res.sendStatus(204); // Sends "No Content"68});6970app.get('/data', (req, res) => {71// send() handles different types automatically72res.send({ key: 'value' }); // Sets Content-Type: application/json73res.send('<h1>HTML</h1>'); // Sets Content-Type: text/html74res.send(Buffer.from('binary data')); // Sets Content-Type: application/octet-stream75});76```7778### File Operations7980Send files and handle file downloads.8182```javascript { .api }83/**84* Transfer file at given path85* @param {string} path - File path86* @param {object} options - Transfer options (optional)87* @param {Function} callback - Callback function (optional)88*/89sendFile(path: string, options?: object, callback?: Function): void;9091/**92* Transfer file as attachment (forces download)93* @param {string} path - File path94* @param {string} filename - Download filename (optional)95* @param {object} options - Transfer options (optional)96* @param {Function} callback - Callback function (optional)97*/98download(path: string, filename?: string, options?: object, callback?: Function): void;99```100101**Usage Examples:**102103```javascript104const path = require('path');105106app.get('/files/:filename', (req, res) => {107const filename = req.params.filename;108const filePath = path.join(__dirname, 'uploads', filename);109110// Send file with automatic content-type detection111res.sendFile(filePath, (err) => {112if (err) {113res.status(404).send('File not found');114}115});116});117118app.get('/download/:filename', (req, res) => {119const filename = req.params.filename;120const filePath = path.join(__dirname, 'downloads', filename);121122// Force download with custom filename123res.download(filePath, 'custom-name.pdf', (err) => {124if (err) {125res.status(404).send('File not found');126}127});128});129```130131### Status and Headers132133Manage HTTP status codes and response headers.134135```javascript { .api }136/**137* Set HTTP status code138* @param {number} code - HTTP status code139* @returns {Response} Response object for chaining140*/141status(code: number): Response;142143/**144* Set response header field145* @param {string} field - Header field name146* @param {string|string[]} val - Header value(s)147* @returns {Response} Response object for chaining148*/149set(field: string, val: string | string[]): Response;150151/**152* Set multiple response header fields with object153* @param {object} fields - Object with header field names and values154* @returns {Response} Response object for chaining155*/156set(fields: { [key: string]: string | string[] }): Response;157158/**159* Set response header field (alias for set)160* @param {string} field - Header field name161* @param {string|string[]} val - Header value(s)162* @returns {Response} Response object for chaining163*/164header(field: string, val: string | string[]): Response;165166/**167* Set multiple response header fields with object (alias for set)168* @param {object} fields - Object with header field names and values169* @returns {Response} Response object for chaining170*/171header(fields: { [key: string]: string | string[] }): Response;172173/**174* Get response header field value175* @param {string} field - Header field name176* @returns {string|undefined} Header value or undefined177*/178get(field: string): string | undefined;179180/**181* Append additional header values182* @param {string} field - Header field name183* @param {string|string[]} val - Value(s) to append184* @returns {Response} Response object for chaining185*/186append(field: string, val: string | string[]): Response;187188/**189* Add field to Vary header190* @param {string} field - Field name to add to Vary191* @returns {Response} Response object for chaining192*/193vary(field: string): Response;194```195196**Usage Examples:**197198```javascript199app.get('/api/data', (req, res) => {200// Set status and headers201res.status(200)202.set('Content-Type', 'application/json')203.set('X-API-Version', '1.0')204.json({ data: 'response' });205});206207app.get('/custom-headers', (req, res) => {208// Multiple ways to set headers209res.header('X-Custom', 'value');210res.set({211'X-Multiple': 'header1',212'X-Another': 'header2'213});214215// Append to existing headers216res.append('Set-Cookie', 'cookie1=value1');217res.append('Set-Cookie', 'cookie2=value2');218219// Add to Vary header for caching220res.vary('User-Agent');221222res.send('Response with custom headers');223});224```225226### Content Type Management227228Set and manage response content types.229230```javascript { .api }231/**232* Set Content-Type HTTP header233* @param {string} type - MIME type or file extension234* @returns {Response} Response object for chaining235*/236type(type: string): Response;237238/**239* Alias for type() method240* @param {string} type - MIME type or file extension241* @returns {Response} Response object for chaining242*/243contentType(type: string): Response;244245/**246* Respond based on Accept header using callback object247* @param {object} obj - Object with content type keys and handler functions248* @returns {Response} Response object for chaining249*/250format(obj: object): Response;251```252253**Usage Examples:**254255```javascript256app.get('/api/data', (req, res) => {257res.type('json').send('{"message": "JSON string"}');258// Sets Content-Type: application/json259});260261app.get('/file.xml', (req, res) => {262res.contentType('xml');263res.send('<root><data>XML content</data></root>');264});265266app.get('/multi-format', (req, res) => {267// Respond with different formats based on Accept header268res.format({269'text/plain': () => {270res.send('Plain text response');271},272'text/html': () => {273res.send('<h1>HTML response</h1>');274},275'application/json': () => {276res.json({ message: 'JSON response' });277},278'default': () => {279res.status(406).send('Not Acceptable');280}281});282});283```284285### Cookie Management286287Set and clear HTTP cookies.288289```javascript { .api }290/**291* Set cookie with name and value292* @param {string} name - Cookie name293* @param {any} value - Cookie value294* @param {object} options - Cookie options (optional)295* @returns {Response} Response object for chaining296*/297cookie(name: string, value: any, options?: object): Response;298299/**300* Clear cookie by name301* @param {string} name - Cookie name302* @param {object} options - Cookie options (optional)303* @returns {Response} Response object for chaining304*/305clearCookie(name: string, options?: object): Response;306```307308**Usage Examples:**309310```javascript311app.post('/login', (req, res) => {312// Set authentication cookie313res.cookie('token', 'jwt-token-here', {314httpOnly: true,315secure: true,316maxAge: 86400000, // 24 hours317sameSite: 'strict'318});319320res.json({ message: 'Logged in successfully' });321});322323app.post('/logout', (req, res) => {324// Clear authentication cookie325res.clearCookie('token', {326httpOnly: true,327secure: true,328sameSite: 'strict'329});330331res.json({ message: 'Logged out successfully' });332});333334app.get('/preferences', (req, res) => {335// Set preference cookies336res.cookie('theme', 'dark');337res.cookie('language', 'en', { maxAge: 31536000000 }); // 1 year338339res.send('Preferences saved');340});341```342343### Navigation and Redirects344345Handle URL redirections and set location headers.346347```javascript { .api }348/**349* Set Location header350* @param {string} url - URL for Location header351* @returns {Response} Response object for chaining352*/353location(url: string): Response;354355/**356* Redirect to URL with optional status code357* @param {string} url - Redirect URL358*/359redirect(url: string): void;360361/**362* Redirect to URL with specific status code363* @param {number} status - HTTP status code (3xx)364* @param {string} url - Redirect URL365*/366redirect(status: number, url: string): void;367368/**369* Set Content-Disposition header to attachment370* @param {string} filename - Attachment filename (optional)371* @returns {Response} Response object for chaining372*/373attachment(filename?: string): Response;374```375376**Usage Examples:**377378```javascript379app.post('/login', (req, res) => {380if (authenticateUser(req.body)) {381// Redirect to dashboard after successful login382res.redirect('/dashboard');383} else {384res.redirect(401, '/login?error=invalid');385}386});387388app.get('/old-page', (req, res) => {389// Permanent redirect390res.redirect(301, '/new-page');391});392393app.get('/download-report', (req, res) => {394// Set as downloadable attachment395res.attachment('monthly-report.pdf');396// Could follow with res.sendFile() or res.send()397});398399app.get('/external-link', (req, res) => {400// Set location without redirecting401res.location('https://example.com');402res.send('Link available in Location header');403});404```405406### Link Headers407408Manage Link HTTP headers for resource relationships.409410```javascript { .api }411/**412* Set Link header with given link object413* @param {object} links - Object with link relationships414* @returns {Response} Response object for chaining415*/416links(links: object): Response;417```418419**Usage Examples:**420421```javascript422app.get('/api/users', (req, res) => {423// Set pagination links424res.links({425next: '/api/users?page=2',426prev: '/api/users?page=1',427last: '/api/users?page=10'428});429430res.json({ users: [], page: 1 });431});432```433434### Template Rendering435436Render view templates with local variables.437438```javascript { .api }439/**440* Render view template with local variables441* @param {string} view - View name442* @param {object} locals - Local variables for template (optional)443* @param {Function} callback - Callback function (optional)444*/445render(view: string, locals?: object, callback?: Function): void;446```447448**Usage Examples:**449450```javascript451app.get('/', (req, res) => {452// Render template with data453res.render('index', {454title: 'Home Page',455user: req.user,456posts: getPosts()457});458});459460app.get('/error', (req, res) => {461// Render with callback462res.render('error', { message: 'Something went wrong' }, (err, html) => {463if (err) {464res.status(500).send('Render error');465} else {466res.send(html);467}468});469});470```471472### Response Properties473474```javascript { .api }475/**476* Local variables scoped to the request, useful for exposing request-level information to templates477*/478locals: { [key: string]: any };479480/**481* Reference to the Express application instance482*/483app: Application;484485/**486* Reference to the request object for this response487*/488req: Request;489```490491### Standard Node.js Properties492493The Express response object extends Node.js ServerResponse, providing access to all standard HTTP response properties and methods:494495```javascript { .api }496/**497* HTTP status code498*/499statusCode: number;500501/**502* HTTP status message503*/504statusMessage: string;505506/**507* Response headers object508*/509headers: { [key: string]: string | string[] };510511/**512* True if headers have been sent513*/514headersSent: boolean;515```516517**Usage Examples:**518519```javascript520app.get('/status-check', (req, res) => {521console.log('Current status:', res.statusCode); // 200 (default)522console.log('Headers sent:', res.headersSent); // false523524res.status(204).send();525526console.log('Headers sent:', res.headersSent); // true527});528```