0

i build a simple api that has a response body of { "name": "saud", "age": "22" }

it is hosted on http://localhost:7283/saud using Node js express

app.get('/saud',(req,res)=>{res.status(200).send({name:'saud',age:'22'}) } );

it works if i access from a (physical mobile/Insomnia/Chrome) but when i host my Web app on localhost and the request is sent. i keep getting CircularProgressIndicator (meaning that there is no response in future)

this is my code for flutter:

    Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: SingleChildScrollView(
          child: FutureBuilder<http.Response>(
        future: getUrl(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            print(json.decode(snapshot.data!.body));
            return Text(json.decode(snapshot.data!.body).toString());
          }
          return CircularProgressIndicator();
        },
      )),
    );
  }

Future<http.Response> getUrl() async {
        return http.get(Uri.parse('http://192.168.92.226:7283/saud/'));
      }

this exact same code is working perfectly for mobile app or insomnia

insomnia poco x3 pro

network tab dev tools

Saud Ahmed
  • 65
  • 6
  • Could you please show the request in the network tab of the developer tools ? It could be a cors problem or something like this. – jeremynac Sep 13 '21 at 07:27
  • @jeremynac attached a screenshot in the OP – Saud Ahmed Sep 13 '21 at 07:39
  • 1
    @jeremynac it is a cors problem the red button on top left shows this: Access to XMLHttpRequest at 'http://192.168.92.226:7283/saud/' from origin 'http://localhost:62894' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. – Saud Ahmed Sep 13 '21 at 07:41

1 Answers1

0

The "CORS policy: No 'Access-Control-Allow-Origin'" error means that the backend is blocking your frontend request because it's running on http://localhost on a different port than the backend port. To fix it, just use the cors package on the backend:

app.use(cors({
    origin: '*'
}));

If not working:

app.use(cors({
    origin: 'http://localhost:<yourFlutterWebPort>'
}));

If it's still not working, your might consider using a proxy or a http-tunnel like ngrok

jeremynac
  • 1,204
  • 3
  • 11