【问题标题】:Angular 7 not sending post data to apiAngular 7不将发布数据发送到api
【发布时间】:2019-02-20 16:08:23
【问题描述】:

我有一个asp.net 后端服务。后端 api 在postman

上运行良好

但是从角度做同样的事情是行不通的。正文不会发送到服务器。我正在使用角度 7。

这是我的代码。

乳品服务

public addNewDairy(value) {
    return this.http.post(this.apiUrl + "dairy", value)
      .pipe(
        map(success => success),
        catchError(this.hes.handleError) // then handle the error
      );
  }

和组件

requestForRegistration(value) {
    this.jqxLoader.open();
    this.ds.addNewDairy(value).subscribe(res => {
      this.jqxLoader.close();
      this.message = "Requested for activation.";
      this.notification.open();
    }, error => {
      console.log(error);
      this.jqxLoader.close();
      this.message = "Something went wrong please try again!";
      this.notification.open();
    });
  }

【问题讨论】:

  • 你调试过并确认你的值不是未定义的吗?
  • 是的,先生。有价值呈现。它正在addNewDairy 方法中打印
  • "Http" 已弃用。你能改用 HttpClient 吗?
  • 使用了相同的 HttpClient 并从 @angular/common/http 导入

标签: angular typescript asp.net-web-api httpclient


【解决方案1】:

204 来自浏览器作为跨域请求的一部分发送的 OPTIONS 请求。一旦 OPTIONS 请求以 200 成功返回,您的真实请求就会上升。 Postman 不会发送 OPTIONS 请求,因为在该实例中您将直接访问 API。你的 Angular 看起来不错 - 我会在你的 asp.net 后端验证是否启用了 CORS - 请参阅此处https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors

【讨论】:

  • 我已经使用 `app.UseCors(builder => builder.WithOrigins("localhost:4200"));`在startup.cs 启用了 CORS;`
猜你喜欢
  • 2019-01-22
  • 1970-01-01
  • 2022-06-14
  • 1970-01-01
  • 2017-01-15
  • 2018-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多