Enable CORS while an XMLHttpRequest error occurs in flutter web

18,617

Solution 1

For enabling cors on my server and to resolve XMLHttpRequest error in flutter web

I am using this in my .htaccess file for allowing access to certain domains only

 <ifModule mod_headers.c>
    SetEnvIf Origin "http(s)?://(localhost:25120|domain.com|domain2.com)$" AccessControlAllowOrigin=$0
    Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
    Header always set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
 </ifModule>    

Solution 2

For anyone who is using node.js server, enable cors support in your server side code.

  1. npm i cors express
  2. In index.js or server.js -
const express = require("express");

const app = express();
var cors = require("cors");
app.use(cors()); 

This should fix cors issue with flutter web

Share:
18,617
OceanL
Author by

OceanL

Updated on June 07, 2022

Comments

  • OceanL
    OceanL almost 2 years

    when I will add data to the database using the function, and on the server I have added Access-Control-Allow-Origin so that it is not blocked by CORS, but still error when I looked in the browser console tools tab console

    Access to XMLHttpRequest at 'https://int.goo.id/api/pg/sso.register' from origin 'http://127.0.0.1:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
    

    how to deactivate CORS??

  • Mohsin Khan
    Mohsin Khan about 4 years
    where to add .htaccess file like near to pubspec.yml ? or where Please help me
  • Vicky Salunkhe
    Vicky Salunkhe about 4 years
    .htaccess file will be stored on your server index directory not on your mobile app's directory
  • Atul Chaudhary
    Atul Chaudhary almost 3 years
    is there is any alternate solution for this, still facing the same issue ???
  • icyNerd
    icyNerd almost 3 years
    can you be more clear as to where the .htaccess file is?
  • Mofidul Islam
    Mofidul Islam over 2 years
    great its working for me
  • Hossein Yousefpour
    Hossein Yousefpour about 2 years
    @icyNerd Create a .htaccress file on your server where you published the built web files. (Next to the main.dart.js, etc.)