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
1,351 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://yourdomain.com", "https://yourflutterapp.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: https://yourdomain.com and https://yourflutterapp.com. 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

How to Deserialize a list of objects from json in flutter Ask Question?

To deserialize a list of objects from ...READ MORE

answered Mar 28, 2023 in Flutter by vishalini
1,618 views
0 votes
1 answer

flutter web build JS function with external JS library

The code you provided seems to be ...READ MORE

answered Apr 10, 2023 in Flutter by vinayak
1,520 views
0 votes
1 answer

Xcode Cloud not building my Flutter Project

It's difficult to determine the exact cause ...READ MORE

answered Apr 11, 2023 in Flutter by Anitha
1,285 views
0 votes
1 answer

Linking 3 Flutter Projects in One Flutter Project

Yes, it is possible to combine multiple ...READ MORE

answered Mar 20, 2023 in Flutter by vinayak
337 views
+1 vote
1 answer
+2 votes
1 answer
0 votes
1 answer

How to get barcode from PDA scanner device in flutter

It's possible that the data sent by ...READ MORE

answered Apr 3, 2023 in Flutter by seena
1,196 views
0 votes
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP