I think I've gone through 100 Stackoverflow posts about enabling CORS with AngularJS. Most of them reference adding headers to the API. Is there anyway to solve this issue if you don't have direct access to edit the API you're using?
I think I've gone through 100 Stackoverflow posts about enabling CORS with AngularJS. Most of them reference adding headers to the API. Is there anyway to solve this issue if you don't have direct access to edit the API you're using?
Share Improve this question asked Mar 17, 2016 at 18:00 davedave 3555 silver badges11 bronze badges 2- Why you don't want to add headers ? – Thanigainathan Commented Mar 17, 2016 at 18:02
- @Thanigainathan many third-party APIs were designed for clients other than the browser, which typically don't enforce CORS (you won't find it in Java's HttpClient or curl, for example). Using them from a browser requires headers they simply omitted. Same goes for older APIs. – ssube Commented Mar 17, 2016 at 18:04
2 Answers
Reset to default 5If you need CORS headers but the original API doesn't provide them, you can set up a small proxy server and call through that. Using HAProxy or Nginx, you can restrict the destinations to just the API and add headers on the way through. You may also be able to set up the proxy on a path under the site's origin and avoid headers altogether.
To set up your own CORS proxy with HAProxy, you just need to add a few config lines:
listen http-in
mode http
listen *:80
# Add CORS headers when Origin header is present
capture request header origin len 128
http-response add-header Access-Control-Allow-Origin %[capture.req.hdr(0)] if { capture.req.hdr(0) -m found }
rspadd Access-Control-Allow-Headers:\ Origin,\ X-Requested-With,\ Content-Type,\ Accept if { capture.req.hdr(0) -m found }
I prefer to use HAProxy, because it's incredibly resource-efficient.
With Nginx, you need a little bit more configuration as the headers and proxy are set up separately:
upstream api_server {
server apiserver.;
}
server {
charset UTF-8;
listen 80;
root /home/web/myclient;
index index.html;
server_name myclient.;
location /api/ {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://api_server/;
proxy_ssl_session_reuse off;
proxy_set_header Host $http_host;
proxy_redirect off;
}
location ~ /\. {
deny all;
}
location / {
try_files $uri;
}
}
Both examples are copied from the linked blog posts in case they ever vanish. I did not write either of them.
If you use Mozilla Firefox there is an Add-On called "cors everywhere". If you install it you can activate and disable it on every site you want and it works like a charm.