You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular2+调用NodeJS API时自定义Header遭CORS拦截的问题排查求助

Alright, let's figure out why your CORS request is failing when adding custom headers, and fix this step by step.

The core issue here is that when you add custom headers like Authorization and X-QWEMP-data, the browser triggers a preflight OPTIONS request to check if the server allows these headers. Your current CORS configurations either have syntax errors, conflicting settings, or aren't properly handling this preflight request.

Let's start with the most likely fixes:

1. Fix your manual CORS middleware (if you're using it)

First, you had a typo in your manual CORS code: set.headers should be res.setHeader. Also, make sure to send a proper 200 status code for OPTIONS requests instead of just res.send():

app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Headers', 'Authorization,X-QWEMP-data,Content-Type');
  res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
  
  if (req.method === 'OPTIONS') {
    res.sendStatus(200); // Send a clear 200 response for preflight
    return;
  }
  next();
});

But honestly, using the cors library is more reliable—so let's focus on getting that configured correctly.

2. Correct your cors library configuration

Your current cors setup has two critical issues:

  • preflightContinue: true tells the library not to finish the OPTIONS request, leaving it up to subsequent middleware (like bodyParser) to handle it. But OPTIONS requests don't have a body, so bodyParser will throw errors, causing the preflight to fail.
  • If you set credentials: true, you cannot use * as the origin—browsers block this for security. Only use credentials: true if your Angular app is sending cookies/HTTP auth, and specify the exact origin instead.

Here's the fixed cors config:

Case 1: Your Angular app doesn't send cookies/credentials
app.use(cors({
  methods: 'GET,POST,PUT,DELETE,OPTIONS',
  allowedHeaders: 'Authorization,X-QWEMP-data,Content-Type',
  exposedHeaders: 'Authorization,X-QWEMP-data,Content-Type'
}));
Case 2: Your Angular app needs to send credentials (e.g., cookies)
app.use(cors({
  origin: 'http://localhost:4200', // Replace with your Angular app's actual URL
  methods: 'GET,POST,PUT,DELETE,OPTIONS',
  allowedHeaders: 'Authorization,X-QWEMP-data,Content-Type',
  exposedHeaders: 'Authorization,X-QWEMP-data,Content-Type',
  credentials: true
}));

3. Clean up conflicts

  • Remove any manual CORS middleware when using the cors library—having both will cause conflicting headers.
  • Restart your Node.js server after updating the config, and clear your browser cache (sometimes old CORS responses are cached).

4. Verify the preflight request

Open your browser's DevTools > Network tab, find the OPTIONS request that fails, and check the Response Headers:

  • Ensure Access-Control-Allow-Origin matches your allowed origin (either * or your Angular URL)
  • Ensure Access-Control-Allow-Headers includes Authorization, X-QWEMP-data, and Content-Type
  • The response status code should be 200 (or 204)

5. Double-check your Angular Interceptor

Your interceptor code looks mostly correct, but make sure you're passing the cloned request to next.handle() (I assume you are, since you didn't show the full interceptor):

// Angular Interceptor example (TypeScript)
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  const idToken = localStorage.getItem('idToken');
  const encrypted = 'your-encrypted-data';
  
  if (idToken && encrypted) {
    const clonedReq = req.clone({
      headers: req.headers
        .set('Authorization', `Bearer ${idToken}`)
        .set('X-QWEMP-data', encrypted)
    });
    return next.handle(clonedReq);
  }
  return next.handle(req);
}

This ensures you're preserving the original request headers (like Content-Type) while adding your custom ones.

Bonus: Check for server-side errors

Look at your Node.js server logs (you're using morgan, so you should see requests coming in). If the OPTIONS request isn't showing up, it might be blocked by a reverse proxy (like Nginx) or firewall. If you're using Nginx, add this to your config to handle preflight:

if ($request_method = OPTIONS) {
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;
    add_header Access-Control-Allow-Headers Authorization,X-QWEMP-data,Content-Type;
    return 204;
}

Try these steps, and your CORS issue should be resolved. If not, share the exact response headers from the failed OPTIONS request and your server logs, and we can dig deeper.

内容的提问来源于stack exchange,提问作者Alexis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 16:39:06