基于npm request包的拦截器:Express三层架构请求转发与认证处理问询
request Package Got it, let’s walk through exactly how to set up this token-handling logic in your Express middleware layer. I’ve broken this down into actionable steps that fit your three-tier architecture perfectly:
1. Install Dependencies
First, make sure you have the request package installed (plus express-session to store the auth token securely across user requests):
npm install request express-session --save
2. Configure Express Session for Token Storage
We’ll use express-session to persist the auth token between requests. For production, swap the default in-memory store with something like Redis or MongoDB to avoid losing sessions on server restarts:
const express = require('express'); const session = require('express-session'); const request = require('request'); const app = express(); // Session configuration (tweak for production!) app.use(session({ secret: 'your-strong-unique-secret-key', // Use an env var in production resave: false, saveUninitialized: false, cookie: { secure: process.env.NODE_ENV === 'production', // Only send cookie over HTTPS in prod httpOnly: true, // Prevent XSS access to the cookie maxAge: 24 * 60 * 60 * 1000 // 1 day expiry } })); // Parse JSON request bodies (for Angular's AJAX requests) app.use(express.json());
3. Handle Login & Store the Auth Token
Create a route to forward login requests to your external API, then save the returned token in the user’s session:
// Login endpoint (matches what your Angular frontend calls) app.post('/api/login', (req, res) => { // Forward the login request to your external auth API request.post({ url: 'https://your-external-api-server.com/auth/login', json: req.body // Pass along the username/password from Angular }, (error, apiResponse, body) => { if (error) { return res.status(500).json({ error: 'Failed to connect to authentication server' }); } // If the API returns a valid token, store it in the session if (body.token) { req.session.authToken = body.token; } // Pass the external API's response directly back to Angular res.status(apiResponse.statusCode).json(body); }); });
4. Create an Authenticated Request Wrapper
We’ll wrap the request package to automatically attach the auth token to every forwarded request. This acts like an interceptor for your outbound calls:
// Wrapper that adds the auth token to request headers if available const getAuthenticatedRequest = (req) => { const headers = {}; if (req.session.authToken) { // Adjust the header format to match what your external API expects (e.g., Bearer token) headers['Authorization'] = `Bearer ${req.session.authToken}`; } return request.defaults({ headers, json: true // Assume all API communication uses JSON }); };
5. Set Up Universal Request Forwarding
Create a catch-all route to forward all other frontend requests to the external API, using our authenticated wrapper:
// Forward all /api/proxy/* requests to the external API app.use('/api/proxy', (req, res) => { // Build the target URL by stripping the /api/proxy prefix const targetUrl = `https://your-external-api-server.com${req.url}`; // Use our authenticated request wrapper to send the request const authenticatedReq = getAuthenticatedRequest(req); authenticatedReq({ url: targetUrl, method: req.method, body: req.body }) .on('response', (apiResponse) => { // Handle token expiry: if the API returns 401, clear the stored token if (apiResponse.statusCode === 401) { delete req.session.authToken; } }) .pipe(res); // Pipe the external API's response directly back to Angular });
Key Notes for Production
- Session Storage: Replace the default in-memory session store with a persistent option like
connect-redisto scale across multiple Express instances. - Security: Always use HTTPS in production to protect the auth token in transit.
- Error Handling: Add a global error handler in Express to catch and format any forwarding errors consistently for your Angular frontend.
- Token Format: Adjust the
Authorizationheader format if your external API uses a different scheme (e.g., API keys instead of Bearer tokens).
内容的提问来源于stack exchange,提问作者shafeequemat

