Simple Way to get Around CORS

CORS gets in the way for many web developers when using AJAX requests. This post details how to get around it.

My helpful screenshot

For security reasons, ajax will not allow cross site scripting by default.

Getting around CORS

There are a lot of ways to get around this, but for today, I’d like to go over a simple way to do it through docker and nginx. What we are going to build is a simple container that will proxy requests to the desired api using nginx’s wonderful proxy_pass feature.

Assuming you have docker installed, first lets go an grab nginx.

$ docker pull nginx:latest

Next lets setup the nginx config locally. Create a file named conf/api.conf, it should look like this.

# conf/api.conf

server {
    listen       80;
    server_name  default;

    location /your_proxy_path {
      proxy_pass https://apitoproxy.com;
      add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
      add_header 'Access-Control-Allow-Origin' '*';
    }
}

Next run docker and attach the correct volume

$ docker run -d -p 80:80 -v $(pwd)/conf:/etc/nginx/conf.d:ro nginx

Verify it works

My helpful screenshot