3

I have dotnet core web api app which returns following error when trying to POST request from another computer or the same host via IP address:

XMLHttpRequest cannot load http://10.50.1.46:2280/api/login/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://10.50.1.46:8080' is therefore not allowed access. The response had HTTP status code 400.

Client app is vue.js app. Here is login method snippet which fails:

    login: function(e) {
        e.preventDefault();
        this.connectionError = false;
        this.loginError = false;

        var headers = { 'Content-Type': 'application/json' };
        var loginUrl = 'http://10.50.1.46:2280/api/login/';
        var data = {Login: this.user.login, Password: this.user.password};

        console.log('Sending login request for user : ' + this.user.login);

        this.$http.post(loginUrl, data, {headers: headers})
            .then(response => {
                // get body data
                var data = response.body.data;
                setCredentials(this.user.login, data.accessToken, data.refreshToken);
                this.$router.push('/home');
            }, response => {
                console.log(response);
                if(response.status == 0) {
                    this.connectionError = true;
                } else {
                    this.loginError = true;
                }
            });

    }

Here is my Startup.cs file. And here are request and response headers info

Any idea how to fix it?

gandra404
  • 5,727
  • 10
  • 52
  • 76
  • 3
    So the core of your problem is that your server apparently does not answer the CORS preflight request properly, hence the error message. You could either remove the need for a preflight request by removing the 'Content-Type' header or you teach your server how to handle CORS preflights, which I don't know how to do :-(. – Daniel Hintze Jul 12 '17 at 21:33
  • See https://stackoverflow.com/questions/43459226/405-method-options-not-allowed-in-asp-net-web-api-controller/43461131#43461131 – sideshowbarker Jul 13 '17 at 02:08

1 Answers1

7

on Startup.cs in ConfigureServices enter this lines:

 services.AddCors(options => options.AddPolicy("Cors",
            builder =>
            {
                builder.
                AllowAnyOrigin().
                AllowAnyMethod().
                AllowAnyHeader();
            }));

and in Configure method enter this line:

app.UseCors("Cors");

More info here: https://learn.microsoft.com/en-us/aspnet/core/security/cors

tokenaizer
  • 208
  • 1
  • 5
  • 17