Reputation: 6071
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?
Upvotes: 3
Views: 3377
Reputation: 208
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
Upvotes: 7