【问题标题】:Angular 6 Basic Auth Post Request to .NET Core APIAngular 6 对 .NET Core API 的基本身份验证发布请求
【发布时间】:2019-01-31 05:38:28
【问题描述】:

这个问题已经发布了很多次,但我尝试了几种解决方案,但它们都不适合我。我正在制作一个 API 服务,需要使用基本身份验证来获取承载令牌以用于其他端点。 API 是用 .NET Core 编写的。

我的代码很简单:

private GetToken() {
    let delta = new Date().getTime() - this.tokenTimestamp.getTime();

    const options = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json', 
            'Cache-Control': 'no-cache',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Headers': 'Origin, Content-Type, X-Auth-Token, content-type',
            'Authorization': 'Basic ' + btoa(this.user + ':' + this.pass)
        })
    };

    console.log(options);

    if (delta >= 60000) {
        this.http.post<Response>(this.url + '/api/Auth/Token/', { username: this.user, password: this.pass }, options)
        .subscribe(
        (val) => {
            console.log("POST call successful value returned in body", val);
        },
        response => {
            console.log("POST call in error", response);
        },
        () => {
            console.log("The POST observable is now completed.");
        });
    }
}

我在控制台中收到 CORS 错误(我认为):

非常感谢您的帮助!

【问题讨论】:

  • CORS 应该在服务器而不是客户端处理。您无能为力,您需要更新您的 API 以发送 access-control-allow-origin 标头
  • 我正在从 Postman 和 SQL Server 进行测试,并且 POST 运行良好......我认为这是我在 Angular(客户端)中做错的事情。
  • postman 和 sql server 不使用客户端 JS 发送请求,这就是 CORS 的问题.. 这就是本网站上所有答案都告诉你要做的事情

标签: angular api post .net-core angular6


【解决方案1】:

即使看起来存在 CORS 问题(可能真的存在也可能不存在),首先您需要解决 404 Not Found 错误。在我们的应用程序中,当出现 404 Not Found 时,即使 CORS 配置已完美设置,404 错误通常也会伴随着 CORS 错误。

要对此进行测试,请打开 Postman。向您的 localhost:50897/api/Auth/Token/ 创建一个 POST 请求,看看您是否仍然收到 404。如果是,您将考虑确保您的端点是好的。

编辑:

在你的 Startup.cs 中,确保你在 Configure(..) { }

中有这个
app.UseCors(builder => builder
                        .WithOrigins("http://localhost:4200", "url2") // url2 would be the IP address that your angular app is deployed under in IIS
                        .AllowCredentials()
                        .AllowAnyHeader()
                        .AllowAnyMethod());

【讨论】:

  • 感谢@dexter——它在 Postman 中运行良好。我在发帖之前确定了这一点。
  • @brandoncluff 在这种情况下,请显示您在 Startup.cs 中的 Configure() 的外观或查看编辑。
  • 叮叮叮!这解决了我的问题。我正在 localhost 上测试 .NETCore API 和 Angular6 应用程序...当我部署时,我还需要这个 app.UseCors 构建器吗?
猜你喜欢
  • 2019-05-05
  • 1970-01-01
  • 2019-03-29
  • 2020-09-05
  • 2015-10-21
  • 2020-10-15
  • 1970-01-01
  • 1970-01-01
  • 2019-08-08
相关资源
最近更新 更多