Angular 5请求资源无Access-Control-Allow-Origin头问题求助
Hey there, let's break down what's going on here and fix that frustrating CORS error. First, a critical misunderstanding to clear up: those Access-Control-Allow-* headers you're adding to your request are response headers that the server needs to send back, not request headers your Angular app should include. Your browser checks for these headers in the server's response to approve cross-origin requests—sending them from the client does nothing to resolve the issue.
Actionable Solutions Based on Your Situation
1. If you have control over the backend server
Configure your server to return the required CORS response headers. At minimum, you need these:
Access-Control-Allow-Origin: Set this to your Angular app's URL (likehttp://localhost:4200for development) or*(for public APIs, note this disables some security features like credentials).Access-Control-Allow-Headers: Include headers your request uses, such asAuthorizationandContent-Type.Access-Control-Allow-Methods: List the HTTP methods your API supports (GET, PUT, POST, DELETE, etc.).
For example, if your backend uses Node.js/Express, you can use the cors middleware to simplify setup:
const cors = require('cors'); app.use(cors({ origin: 'http://localhost:4200', allowedHeaders: ['Authorization', 'Content-Type'], methods: ['GET', 'PUT', 'POST', 'DELETE'] }));
2. If you can't modify the backend (development environment only)
Use Angular CLI's proxy configuration to forward requests through your dev server—this bypasses the browser's CORS check entirely:
- Create a
proxy.conf.jsonfile in your project root:
Replace{ "/api": { "target": "https://your-api-domain.com", "secure": false, "changeOrigin": true } }/apiwith your API's path prefix, andhttps://your-api-domain.comwith your actual API URL. - Update your
angular.jsonto use this proxy when serving the app:"architect": { "serve": { "options": { "proxyConfig": "proxy.conf.json" } } } - Restart your Angular dev server (
ng serve), then update your API calls to use the dev server URL (e.g.,http://localhost:4200/api/your-endpointinstead of the direct API address).
3. Production Environment Workaround
If you can't configure the backend, deploy your Angular app and API under the same domain using a reverse proxy (like Nginx). The proxy will forward requests from your app to the API, making them appear same-origin to the browser and eliminating CORS issues.
Cleaned-Up Angular Code
Remove those unnecessary Access-Control-* headers from your request—here's the fixed version:
getMethod() { let headers = new Headers(); headers.append("Authorization", "Basic " + btoa("username:password")); headers.append("Content-Type", "application/x-www-form-urlencoded"); let options = new RequestOptions({ headers: headers }); // Rest of your request logic, for example: return this.http.get('your-api-url', options) .map(res => res.json()) .catch(err => Observable.throw(err)); }
内容的提问来源于stack exchange,提问作者Mohamed Saber

