Request Object in Express.js
The Request object in Express.js encapsulates all information about an incoming HTTP request. It provides access to request headers, parameters, query strings, and other request-related data.
const express = require('express');
const application = express();
application.listen(3000);
application.get('/profile/:uid', (request, response) => {
// Original request URL string
console.log("URL:", request.originalUrl);
// Protocol string (http, https)
console.log("Protocol:", request.protocol);
// Client IP address
console.log("IP:", request.ip);
// URL path portion
console.log("Path:", request.path);
// Request hostname
console.log("Host:", request.hostname);
// HTTP method
console.log("Method:", request.method);
// Query string object
console.log("Query:", JSON.stringify(request.query));
// Check if request is fresh
console.log("Fresh:", request.fresh);
// Check if request is stale
console.log("Stale:", request.stale);
// Check for secure connection
console.log("Secure:", request.secure);
// Check charset support
console.log("UTF8:", request.acceptsCharsets('utf8'));
// Get specific header value
console.log("Connection:", request.get('connection'));
// All headers as object
console.log("Headers:", JSON.stringify(request.headers, null, 2));
response.send("Profile Data Retrieved");
});
Response Object in Express.js
The Response object handles the server's response to client requests. It provides methods for setting headers, status codes, and sending various types of response data.
Setting Headers
Response headers control how clients interpret the response. Express provides several methods for header manipulation:
// Get and set individual headers
const contentType = response.get('Content-Type');
response.set('Content-Type', 'text/plain');
// Set multiple headers at once
response.set({
'Content-Type': 'application/json',
'Cache-Control': 'no-cache'
});
// Set Location header for redirects
response.location('/login');
// Set Content-Type from file extension
response.type('html');
// Set Content-Disposition for file downloads
response.attachment('./documents/report.pdf');
Setting Status Codes
HTTP status codes idnicate the result of the request proecssing:
response.status(200); // OK
response.status(404); // Not Found
response.status(500); // Internal Server Error
Sending Responses
Multiple methods exist for sending different types of responses:
const express = require('express');
const application = express();
application.listen(3000);
application.get('/', (request, response) => {
const htmlContent = '<html><body><h1>Welcome</h1></body></html>';
response.status(200);
response.set({
'Content-Type': 'text/html',
'Content-Length': Buffer.byteLength(htmlContent)
});
response.send(htmlContent);
});
application.get('/not-found', (request, response) => {
response.status(404).send("Resource not found");
});
Sending JSON Responses
For API endpoints, JSON responses are commonly used:
application.get('/api/data', (request, response) => {
// Configure JSON formatting
application.set('json spaces', 2);
response.json({
institution: "Museum of Science",
established: '1869',
collectionSize: '34M',
departments: ['astronomy', 'biology', 'paleontology', 'zoology']
});
});
application.get('/api/error', (request, response) => {
response.status(500).json({
success: false,
error: "Database connection failed"
});
});
// JSONP for cross-domain requests
application.get('/api/jsonp', (request, response) => {
application.set('jsonp callback name', 'callback');
response.jsonp({
data: "JSONP response"
});
});
Sending Files
Express provides convenient methods for file transfers:
application.get('/download/:file', (request, response) => {
const filename = request.params.file;
response.download('./uploads/' + filename, filename, (error) => {
if (error) {
console.error("File transfer failed:", error);
response.status(500).send("Download error");
}
});
});
application.get('/static/:asset', (request, response) => {
const assetPath = request.params.asset;
response.sendFile(assetPath, {
root: './public',
maxAge: 86400000 // 24 hours
}, (error) => {
if (error) {
response.status(404).send("Asset not found");
}
});
});
Implementing Redirects
Redirects guide clients to different URLs:
application.get('/external', (request, response) => {
response.redirect('https://example.com');
});
application.get('/old-path', (request, response) => {
response.redirect('/new-path');
});
application.get('/new-path', (request, response) => {
response.send("You've been redirected");
});
// Relative redirects
application.get('/section/first', (request, response) => {
response.redirect('../second');
});