如何在Express CORS预检响应中允许Authorization请求头?
Hey there! Let’s work through this CORS issue you’re stuck on—dealing with the Authorization header in preflight responses can be tricky, but I’ve got some steps to get this sorted.
First, let’s clear up a common confusion: If your frontend is directly calling the ViaCEP API from localhost:8021, your Express backend’s CORS configuration won’t help here. CORS rules are enforced by the target server (ViaCEP in this case), not your own backend. If ViaCEP’s server doesn’t include Authorization in its Access-Control-Allow-Headers response, browsers will block the request. That’s why routing requests through your Express server as a proxy is the more reliable approach (and what I’ll focus on below).
Step 1: Fix Your CORS Configuration
Your current config has a tiny but critical issue—case sensitivity for the header name. Browsers typically send Authorization with a capital A, but you’ve listed authorization in lowercase. Let’s update that, plus make the origin explicit (more reliable than setting it to true):
var corsOptions = { origin: 'http://localhost:8021', // Lock this to your dev frontend URL allowedHeaders: ['Content-Type', 'Authorization', 'Content-Length', 'X-Requested-With', 'Accept'], exposedHeaders: ['Authorization'], methods: ['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS'], optionsSuccessStatus: 200, // Fixes compatibility with legacy browsers like IE11 preflightContinue: false }; app.use(cors(corsOptions));
Make sure this cors middleware loads before any of your routes—middleware order matters a lot here!
Step 2: Set Up a Proxy in Express (Recommended)
Since ViaCEP might not allow custom Authorization headers directly, route your frontend requests through your Express server. This way, your backend handles the call to ViaCEP, and your frontend only talks to your own server (avoiding cross-domain issues entirely).
First, install the proxy middleware:
npm install http-proxy-middleware --save
Then add the proxy configuration to your Express app:
const { createProxyMiddleware } = require('http-proxy-middleware'); // Proxy route for ViaCEP requests app.use('/api/viacep', createProxyMiddleware({ target: 'https://viacep.com.br/ws', changeOrigin: true, pathRewrite: { '^/api/viacep': '' }, // Strip the proxy path prefix before forwarding onProxyReq: (proxyReq, req, res) => { // Forward the Authorization header from your frontend to ViaCEP if (req.headers.authorization) { proxyReq.setHeader('Authorization', req.headers.authorization); } } }));
Step 3: Update Your Frontend Axios Call
Now, instead of calling ViaCEP directly, hit your proxy endpoint:
// Replace with your actual JWT token const jwtToken = 'your-jwt-token-here'; axios.get('http://localhost:YOUR_BACKEND_PORT/api/viacep/20021040/json', { headers: { 'Authorization': `Bearer ${jwtToken}` } }) .then((response) => { alert(JSON.stringify(response.data)); // Use response.data for the actual API payload }) .catch((error) => { alert(`Error: ${error.message}`); // More user-friendly error feedback });
Quick Checks to Verify
- Double-check that your frontend is actually sending the
Authorizationheader. You can confirm this using your browser’s DevTools (Network tab, inspect the request headers). - Ensure your Express server runs on a different port than your frontend (e.g., frontend on 8021, backend on 3000).
- If issues persist, check the Network tab for the preflight
OPTIONSrequest—verify the response headers includeAccess-Control-Allow-Headers: Authorization.
内容的提问来源于stack exchange,提问作者felipe muner

