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

Angular 4中出现‘Refused to set unsafe header’错误求助

Fixing "Refused to set unsafe header 'Access-Control-Request-Headers'" in Angular 4

Hey there, let's break down what's going on here and get your API call working properly.

Why You're Seeing This Error

The Access-Control-Request-Headers header is automatically added by the browser during a CORS preflight (OPTIONS) request — you don't need (and aren't allowed) to set it manually in your Angular code. Browsers block frontend code from setting certain CORS-related headers to enforce security rules, which is exactly what's triggering that error.

Also, headers like Access-Control-Allow-Origin are response headers that the server sends back, not request headers you include in your API call. Adding them to your request does nothing and just clutters your code.

Step-by-Step Fixes for Your Code

Here's how to adjust your getData() method to resolve the error:

  • Remove the illegal Access-Control-Request-Headers header entirely
  • Delete the unnecessary Access-Control-Allow-Origin request header
  • Keep only the headers your API actually requires (like Authorization and Content-Type)

Modified Code

getData() {
  // Add only the headers your API actually needs
  let headers = new Headers({
    'Authorization': 'Basic exampletokenexampletokenexampletoken',
    "Content-Type": "application/x-www-form-urlencoded"
  });
  
  let options = new RequestOptions({ headers: headers });
  console.log(headers);
  
  // Get users from api
  return this.http.get(this.apiUrl, options)
    .pipe(map((response: Response) => response.json()));
}

What Else You Might Need to Check

Postman works because it doesn't enforce CORS rules like browsers do. For your local Angular app to work, your backend server needs to properly handle CORS preflight requests. If you have control over the server, make sure it returns these response headers:

  • Access-Control-Allow-Origin: http://localhost:YOUR_ANGULAR_PORT (replace with your actual local port, like 4200)
  • Access-Control-Allow-Headers: Authorization, Content-Type
  • Access-Control-Allow-Methods: GET

These headers tell the browser that your local app is allowed to make requests to the API.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 03:54:11