Cannot fetch from API inside docker container from react app due to 'Access-Control-Allow-Origin'

Viewed 809

I am running azure functions API inside a docker container and I can access it without problem from postman or e.g. chrome, but I fail to access it from react app. I get an error:

from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

If I run API locally not in the container I can use local.settings.json with:

"Host": {
        "LocalHttpPort": 7071,
        "CORS": "*",
        "CORSCredentials": false
    }

if I host API in the cloud I can configure CORS in it, but what about when running it in the docker container?

I've been reading different post trying to figure this out but I still fail to find an answer, or an answer that I can understand :/ Is there something I can modify like local.settings.json or similar? or do I need to modify Dockerfileor something else?

1 Answers

CORS is a browser protection which require an extra header to be resolved . It is a protocol which work between api and browser thus docker can't do anything So you can change either change your api to send the correct headers explained below .

CORS in Docker Engine REST Api - DevOps Stack Exchange

Here we will be directly sending the Access-Control-Allow-Origin header with the it's value set as '*' this will tell the browser to use the same origin resource .

A different approach would be the use of using nginx as a proxy with docker explained below . Here the proxy will change the header .Here you don't have to change your api .

Solving CORS problem on local development with Docker | by Maximillian Xavier | Medium

Related