Home > Enterprise >  CORS Configuration for FastApi
CORS Configuration for FastApi

Time:06-01

I deployed a react app in a server ubuntu 20.04 with nginx 1.18.0 and this is the .conf file.

    server {
        listen 80;

        server_name myapp.com;

        return 301 https://myapp.com$request_uri;

        root /var/www/myapp/build;
        index index.html;

        access_log /var/log/nginx/myapp.access.log;
        error_log /var/log/nginx/myapp.error.log;
        location / {
                try_files $uri /index.html =404;
        }
}

And in this same server I deployed my FastApi

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

origins = [
    "https://myapp.com",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get('/')
def home():
    return {'message': 'Hi app'}

Then from my react app I send a request by axios:

const API = "http://127.0.0.1:8000/";
const response = await axios(API);

My api run in http://127.0.0.1:8000 and I get "Cross Origin Request Blocked: The same origin policy does not allow reading of remote resources at http://127.0.0.1:8000. (Reason: CORS request unsuccessful). Status code: (null)".

This is my request headers that I can see in the browser:

    Accept: application/json, text/plain, */*
    Accept-Encoding: gzip, deflate, br
    Accept-Language: es-MX,es;q=0.8,en-US;q=0.5,en;q=0.3
    Connection: keep-alive
    Host: 127.0.0.1:8000
    Origin: https://myapp.com
    Sec-Fetch-Dest: empty
    Sec-Fetch-Mode: cors
    Sec-Fetch-Site: cross-site
    User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:102.0) Gecko/20100101 Firefox/102.0

In my local I have the same app and api and I don't have the problem, the diference is that the react app run in http://localhost:3000 by npm and of course in my allow origins in my api I have "http://localhost:3000"

CodePudding user response:

Consider setting the header in nginx.

Edit the file /etc/nginx/sites-enabled/yoursite

add: add_header Access-Control-Allow-Origin *;

Like this:

server {
...
...
add_header Access-Control-Allow-Origin *;
...
...
    }
}

And restart your nginx.

Do not enable all origins in a production environment.

CodePudding user response:

adding Access-Control-Allow-Origin in your axios with * value would fix your problem from front-end, sth like this:

header:{
  'Access-Control-Allow-Origin':'*'
}

for backend, you can temporary add this in your server to just work with localhost and when you want to upload it to use the server you can just add Access-Control-Allow-Origin to an only domain that you upload your react project

  • Related