flutterflutter-http

ClientException: XMLHttpRequest error., uri=http://localhost:3000/api/users/allUsers


When Try to work with the api in the Desktop Simulator it is working well but with Edge/Chrome It does not work;

class UserDao {   static const baseUrl = "http://localhost:3000/api"; 
 //Get All Users   static Future<List<UserModel>?> getAllUsers() async
{
    try {
     final resp = await http.get(
        Uri.parse("$baseUrl/users/allUsers"),
        headers: {
          "Accept": "application/json",
          "Access-Control_Allow_Origin": "*",
           "Access-Control-Allow-Headers": "Access-Control-Allow-Origin, Accept"
         },
       );
      var listUser = json.decode(resp.body);
      List<UserModel> users = [];
      listUser.forEach((user) {
         UserModel u = UserModel(
             idUser: user['id_user'],
             firstName: user['firstName'],
            lastName: user['lastName'],
             email: user['lastName'],
            password: user['password']);
         users.add(u);
       });
       return users;
      } 
    catch (err) {
       print(err);
       return null;
     }   
   } 
 }

Solution

  • If we are making requests from a different origin, we need to set up CORS. We can use the cors package:

    const cors = require('cors');
    app.use(cors());  
    
     
    

    add this in the index.js file , it worked for me by adding this