I want to post my solution because my server's CORS is configured correctly (as far as I can tell) and the blocking appears to be a result of the Flutter framework. I think that I solved my problem by removing the Cookie
from the request headers. From my understanding, this is the equivalent of withCredentials = false
. I added the following code right before I made my request:
request.headers.remove('Cookie');
Hopefully this helps someone as I found resolving CORS issues to be the hardest part of publishing a Flutter app to the web. If anyone has any better insight into this issue, then I'm definitely happy to learn more.
If you need to know about my environment, then I am using Django, Django REST framework, and django-cors-headers
:
INSTALLED_APPS = [
...,
"corsheaders",
...,
]
MIDDLEWARE = [
...,
# Place CorsMiddleWare above any middleware that may return a response.
"corsheaders.middleware.CorsMiddleware",
'django.middleware.security.SecurityMiddleware',
...,
]
# Allow CORS from the following domains.
# See: https://github.com/adamchainz/django-cors-headers/tree/main
CORS_ALLOWED_ORIGIN_REGEXES = [
r"^https://\w+\.your-domain\.com$",
]
I have also configured the following for Flutter:
- I have added
--disable-web-security
to $FLUTTER_SDK/packages/flutter_tools/lib/src/web/chrome.dart
- I find it necessary to run
flutter clean & flutter pub get
before flutter build web --web-renderer html
.
- I find that
--web-renderer html
is necessary.
Here is my code for making a POST request from my Flutter app:
import 'package:http/http.dart' as http;
// Define your request.
final client = http.Client();
final request;
final body = jsonEncode(data); // Here you can pass your data.
String idToken = await getUserToken(); // In my case I'm passing a user token.
String url = 'your-api.com';
// Define your headers.
final headers = {
'Content-Type': 'application/json;charset=UTF-8',
'Accept': 'application/json',
'Authorization': 'Bearer $idToken',
}
// Create a POST request.
request = http.Request('POST', Uri.parse(url))
..headers.addAll(headers)
..body = body;
// Ensure the client doesn't add cookies.
request.headers.remove('Cookie');
// Get the response.
final response = await client.send(request).then(http.Response.fromStream);