gpt4 book ai didi

rest - 如何修复 dotnet core web api 中的 No 'Access-Control-Allow-Origin' 错误

转载 作者:行者123 更新时间:2023-12-05 01:18:31 24 4
gpt4 key购买 nike

我有 dotnet core web api 应用程序,它在尝试通过 IP 地址从另一台计算机或同一主机发送 POST 请求时返回以下错误:

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.

客户端应用程序是 vue.js 应用程序。这是失败的登录方法片段:

    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;
}
});

}

这是我的 Startup.cs文件。这里是请求和响应 headers info

知道如何解决吗?

最佳答案

在 ConfigureServices 中的 Startup.cs 中输入以下行:

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

在配置方法中输入这一行:

app.UseCors("Cors");

更多信息在这里:https://learn.microsoft.com/en-us/aspnet/core/security/cors

关于rest - 如何修复 dotnet core web api 中的 No 'Access-Control-Allow-Origin' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45065044/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com