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.