【问题标题】:Unable to fetch custom header in post response using Angular 10无法使用 Angular 10 在发布响应中获取自定义标头
【发布时间】:2021-11-22 15:50:06
【问题描述】:

我正在尝试从 Angular 10 客户端发布响应中获取自定义标头。我可以在浏览器开发网络窗口中看到它,但在我的代码中看不到:

enter image description here

我正在使用以下代码在 Angular 端获取自定义标头:

常量 httpOptions = { 标头:新 HttpHeaders({ 'Content-Type': 'application/json' }) ,withCredentials:false, };

this.loading = true;

  const postedData = { userId : this.f.username.value, password : this.f.password.value, token: "string" };
  this.http.post<any>("https://localhost:44365/api/v1/Credential/", postedData, httpOptions)
  .subscribe(
      data => {
          this.currentUser= data;
          var txt = this.http.options.toString();
          var token = data.headers.get('X_Custom_header');
          var token1 = httpOptions.headers.get('X_Custom_header');
          console.log(data);
          debugger;

看过一篇类似的文章,但在 Angular 中获取标头的代码似乎有所不同: Unable to access custom response header in frontend application

如果在阅读自定义标头时 Angular 侧代码有任何更改,请纠正我。 谢谢。

【问题讨论】:

    标签: angular webapi


    【解决方案1】:

    请参阅文档https://angular.io/guide/http中的http选项“观察”“响应”

    【讨论】:

      【解决方案2】:

      最后我通过在服务器端编写以下代码来获得这个标头:

      app.UseCors(options => options.AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().WithExposedHeaders("X_Custom_header")); //(工作)

      而不是下面的代码:

      app.UseCors("AllowAll"); //(不工作)

      很奇怪,即使我在浏览器上获取自定义标头,我也无法使用简单的 HTTP 发布响应访问它,如附件截图所示。但是在添加了上面的代码之后,我在 Angular 客户端得到了它。

      @krosan:我没有尝试你的方法。但是感谢您提供指导。

      【讨论】:

        猜你喜欢
        • 2017-02-26
        • 1970-01-01
        • 2016-05-27
        • 2013-02-09
        • 2018-04-09
        • 2017-12-10
        • 1970-01-01
        • 2013-08-27
        • 2018-01-26
        相关资源
        最近更新 更多