Angular 4中出现‘Refused to set unsafe header’错误求助
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-Headersheader entirely - Delete the unnecessary
Access-Control-Allow-Originrequest header - Keep only the headers your API actually requires (like
AuthorizationandContent-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-TypeAccess-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

