Can t reach RestAPI FastAPI from my Flutter web - Cross-Origin Request Blocked

0 votes

I have a Linux Server. On that I have two Docker Container.
In the first one I am deploying my Flutter Web and in the other one I am running my RestAPI with FastAPI().
I set both Docker in the same Network, so the communication should work. I also set origins with origins = ['*'] (Wildcard).
I reverse proxy my Flutter web with nginx from the Linux server. I also include *.crt and *.key with nginx to my Flutter Web.

Now, obviously, since my Flutter Web App has https, I cant make a http calls.
When I am trying to make a call with https, I get the Error (from catch): "XMLHttpRequest error".
And in the Browser Console I get: "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://172.21.0.2:8070/. (Reason: CORS request did not succeed). Status code: (null)." (172.21.0.2 is the ip of the Docker and 8070 the port on RestApi running)

I am new to the RestAPI world. I normaly develop only Frontend. But I wanted to give it a try. So I'm sorry if I expressed some things wrong. I am searching since days but cant find a solution to my problem. I would be grateful for any help! (If i missed some information or you need more, feel free to write in the comments, I will update the Question immediately!)
Thank You!

Apr 14, 2023 in Flutter by Ashwini
• 5,430 points
3,360 views

1 answer to this question.

0 votes

It seems like you are facing a CORS (Cross-Origin Resource Sharing) issue while trying to make an API call from your Flutter web app to your FastAPI backend. The error message suggests that the Same Origin Policy (SOP) is blocking the request because it is coming from a different origin (i.e., a different domain, protocol, or port) than the one that served the web page.

To fix this issue, you need to configure CORS properly in your FastAPI backend. FastAPI provides a built-in CORS middleware that allows you to specify which origins are allowed to access your API, what HTTP methods are allowed, what headers are allowed, and whether credentials (cookies) are allowed to be sent.

Here's an example of how to enable CORS in FastAPI:

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

app = FastAPI()

origins = ["https://example.com", "https://app.example.com"]

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

In this example, we are allowing requests from two origins: yourdomain and yourflutterapp . You should replace these with the actual domains or IPs that your Flutter app is using to access your API. You can also use a wildcard (*) to allow any origin.

Make sure you also configure your nginx server to allow CORS by adding the following headers in your server block:

location / {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
    add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain; charset=utf-8';
        add_header 'Content-Length' 0;
        return 204;
    }
}

These headers tell the browser that it's allowed to make cross-origin requests to your FastAPI backend.

After you've made these changes, try to make a request from your Flutter web app again and see if it works. If it still doesn't work, make sure there are no other issues with your network configuration or SSL certificates.

To know more, join our Flutter Course today.

answered Apr 14, 2023 by Akash

Related Questions In Flutter

0 votes
1 answer