Home > Back-end >  Access to XMLHttpRequest at 'localhost:3000/users' from origin 'http://localhost:6252
Access to XMLHttpRequest at 'localhost:3000/users' from origin 'http://localhost:6252

Time:11-05

I am getting this error even though I have allowed CORS in my code. This one is in Node js:

app.use(cors());

app.get('/users', (req, res) => {
    res.set({
        'Access-Control-Allow-Headers': '*',
        'Access-Control-Allow-Methods': 'POST,GET,DELETE,PUT,OPTIONS'
    });

    User.find({}, function(err, users){
        

        if(err)
        {
            return res.status(500).send({err});
        }
        return res.send(users);
    });
});

I am just trying to do a GET request from http://localhost:3000/users using Flutter:

import 'package:retrofit/http.dart' as head;

@head.RestApi(baseUrl: "http://localhost:3000")
abstract class ApiClient {
  factory ApiClient(Dio dio, {String baseUrl}) = _ApiClient;

  @head.GET("/users")
  Future<User> getUsers();
}

Doing this GET request works just fine in Postman but it doesn't work in Flutter because of the CORS. Can anyone help with this?

CodePudding user response:

You only allowed Headers and Method, try adding Access-Control-Allow-Origin and assigning it to * or website URLs.

res.set({
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers': '*',
        'Access-Control-Allow-Methods': 'POST,GET,DELETE,PUT,OPTIONS'
});
  • Related