0

I have a simple local html with some JS that I currently serve via Docker-nginx on localhost:8080 via

docker run -it --name nginx_ol -v  ${PWD}:/usr/share/nginx/html:ro -p 8080:80 -d nginx:alpine

The JS should fetch a JPG from an ("upstream"?) server like so

   var url = http://example.com/foo/bar.jpg
    fetch(url, {method: 'GET', mode:'cors'})

The server is not set up to send the appropriate CORS-headers. Trying to fetch the image this way results in [...] Origin localhost:8080 is not allowed by Access-Control-Allow-Origin as expected.

In my understanding, I have to

  1. configure nginx to reverse proxy the resource to my localhost while adding the necessary CORS headers
  2. Make the request to the proxied location instead

I.e. proxy the image location at http://example.com/foo/bar.jpg to http://localhost/foo/bar.jpg and adjust the fetch URL accordingly.

Being completely green in terms of nginx/proxies, I've read the docs for adding CORS headers for servers I control, and seen examples for adding CORS headers to proxy servers like so.

If I wanted to proxy requests to localhost:8080/foo to http://example.com/foo, I'd expect something like the following to do the job:

 server {
   listen 80;
   server_name localhost;

   add_header 'Access-Control-Allow-Origin';
   add_header ...

    location / { 

      proxy_set_header Host $host;

      add_header 'Access-Control-Allow-Origin' '*';
      add_header 'Access-Control...
      proxy_redirect off;
      proxy_set_header host $host;
      proxy_set_header X-real-ip $remote_addr;
      proxy_set_header X-forward-for $proxy_add_x_forwarded_for;

      proxy_pass http://example.com/;
    }
}

For the request URL localhost:8080/foo/bar.jpg, I'm getting GET 404 (Not found), which tells me that nothing like that is happening.

I'm sorry that this is a matter of basic misunderstanding, but I'm sure users like me who struggle with getting a proxy up and running would benefit from any nudge in the right direction :)

J.B.
  • 43
  • 1
  • 6
  • `proxy_pass http://dummyimage.com/foo` ? – soju Feb 03 '20 at 14:34
  • Try `proxy_pass http://dummyimage.com/;` without `foo`. See [this](https://stackoverflow.com/a/53650827) answer about `proxy_pass` behavior with and without an URI suffix. – Ivan Shatsky Feb 03 '20 at 14:36
  • Sorry for the confusion. I decided against using dummyimage.com/etc for better example syntax but failed to change this instance. proxy_pass is now `http://example.com/` with the url changed accordingly but still now luck, i.e. 404. – J.B. Feb 03 '20 at 14:55
  • Look at the `error.log`, are there any mentions about `no resolver defined to resolve ...`? – Ivan Shatsky Feb 03 '20 at 19:21

0 Answers0