https://daveceddia.com/access-control-allow-origin-cors-errors-in-angular/
Getting this error in your Angular app?
No ' Access-control-allow-origin ' header is present on the requested resource.
You ' ve run afoul of the same Origin Policy – it says that every AJAX request must match the exact host, protocol, and Port of your site. Things that might cause this:
- Hitting a server from a locally-served file (a request from
file:///YourApp/index.html
to http://api.awesome.com
)
- Hitting an external API (a request from
http://yourapp.com
to http://api.awesome.com
).
- Hitting an internal API (a request from
http://yourapp.com
to http://api.yourapp.com
).
- Hitting a different port on the same host (WebApp are on
http://localhost:3000
, API is http://localhost:4000
)
- Requesting over
http
from https
or Vice-versa (requesting https://yourapp.com
from http://yourapp.com
)
To was clear, this is not an Angular error. It afflicts all web apps equally, and most of the fixes we'll look at below is actually modifying the server or the brows Er.
How to fix it
Here is a few ways to solve this problem:
Best:cors header (requires server changes)
CORS (cross-origin Resource sharing) is a-on-the-server to say "I'll accept your request, even though you came from A different origin. " This requires cooperation from the SERVER–SO if you can ' t modify the server (e.g. if you ' re using a external API), this Approach won ' t work.
Modify the server to add the header to Access-Control-Allow-Origin: *
enable Cross-origin requests from anywhere (or specify a domain instead of ). This should solve your problem.
2nd Choice:proxy Server
If you can ' t modify the server, you can run your own proxy. and this proxy can return the Access-Control-Allow-Origin
header if it's not at the same Origin as your page.
Instead of sending API requests to some remote server, you'll make requests to your proxy, which'll forward them to the Remote server. Here is a few proxy options.
3rd CHOICE:JSONP (requires server support)
If CORS and the proxy server don ' t work for you, JSONP. You essentially make a GET request with a callback
parameter:
(get) http://api.example.com/endpoint?callback=foo
The server would wrap the JSON reply in a function call to your callback, where can handle it:
foo({"your": "json", here: true})
There is some downsides, notably that JSONP only supports GET requests and so you still need a cooperative server.
Dev-only:disable same Origin
If This is a development or learning purposes, the easiest thing to do are to disable the same Origin Policy in your Browser. Be aware the if you does this and you ' re opening your browser up to security risks. Follow these instructions:
This was more than a last resort. Modifying the server to support CORS or running a proxy is the best approaches.
Armed and dangerous
You ' re all set now to tackle any Access-Control-Allow-Origin
errors that come your way!
Access-control-allow-origin:dealing with CORS Errors in Angular