简体   繁体   English

Angular 6 Get response headers with httpclient 问题

[英]Angular 6 Get response headers with httpclient issue

I'm using the code below to try to extract a value (ReturnStatus) from the response headers;我正在使用下面的代码尝试从响应标头中提取一个值 (ReturnStatus);

Keep-Alive: timeout=5, max=100
ReturnStatus: OK,SO304545
Server: Apache/2.4.29 (Win32) OpenSSL/1.0.2m

The code;编码;

import { Injectable } from '@angular/core';

import { Account } from './model/account';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from "rxjs";
import { map, filter, catchError, mergeMap } from 'rxjs/operators';

 createOrder(url) : Observable<any> {

  return this._http.get(url, {withCredentials: true, observe: 'response'})
  .pipe(
    map((resp: any) => {
      console.log("response", resp);
      return resp;

    }), catchError( error => {
      console.log("createOrder error",error );
      alert("Create Order Service returned an error. See server log for mote details");
    return throwError("createOrder: " + error)

    })
  );
}

However my console.log just give;但是我的 console.log 只是给;

HttpResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: 
"http://localhost/cgi-bin/dug.cgi/wh?Page… 
plateLocation=C:%5Ctemp%5Corderimporttemplate.txt", ok: true, …}

I've looked on this site and others for the correct way to do this in Angular but to no avail?我已经在这个网站和其他网站上查看了在 Angular 中执行此操作的正确方法,但无济于事? Could someone point me in the right direction please?有人能指出我正确的方向吗?

Many thanks,非常感谢,

Mark.标记。

You need to observe the entire response as described below:您需要观察整个响应,如下所述:

 createOrder(url) : Observable<HttpResponse<Object>>{

    return this.http.get<HttpResponse<Object>>(this.url, {observe: 'response'}).pipe(
         tap(resp => console.log('response', resp))
    );
}

Now inside resp you can access headers An example现在在 resp 里面你可以访问 headers 一个例子

 createOrder(url) : Observable<HttpResponse<Object>>{

    return this.http.get<HttpResponse<Object>>(this.url, {observe: 'response'}).pipe(
         tap(resp => console.log('heaeder', resp.headers.get('ReturnStatus')))
    );
}

If you can't access your custom header as explained above it's because a small set of headers are exposed to javascript by default for security reasons.如果您无法按照上述说明访问自定义标头,那是因为出于安全原因,默认情况下会向 javascript 公开一小组标头。 Probably if you open developer tools and you inspect your response headers you should see the desired one.可能如果您打开开发人员工具并检查您的响应标头,您应该会看到所需的标头。

Who can choose which headers are exposed to javascript?谁可以选择哪些标头暴露给 javascript?

Exposed headers are choosen by the web application (so your webservices, or your backend. Obviously you web application could be written using many languages and/or using many framework. Web 应用程序选择公开的标头(因此您的 Web 服务或后端。显然,您的 Web 应用程序可以使用多种语言和/或使用多种框架编写。

Depending on what you are using you can achieve this goal by different ways.根据您使用的内容,您可以通过不同的方式实现这一目标。

To give you an idea of what you should do I can post my Spring solution.为了让您了解应该做什么,我可以发布我的 Spring 解决方案。 In class extending WebSecurityConfigurerAdapter you should add this two methods:在扩展WebSecurityConfigurerAdapter类中,您应该添加这两个方法:

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
            // we don't need CSRF because our token is invulnerable
            .csrf().disable()
            .cors()
} 


@Bean
public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addExposedHeader("Authorization, x-xsrf-token, Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, " +
            "Content-Type, Access-Control-Request-Method, Custom-Filter-Header");
    config.addAllowedHeader("*");
    config.addAllowedMethod("OPTIONS");
    config.addAllowedMethod("GET");
    config.addAllowedMethod("POST");
    config.addAllowedMethod("PUT");
    config.addAllowedMethod("DELETE");
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}

Note that I've disabled csrf because I'm using JWT.请注意,我禁用了 csrf,因为我使用的是 JWT。 Note that you should refine CorsFilter rules.请注意,您应该细化 CorsFilter 规则。

As you can see I have added Custom-Filter-Header into this line如您所见,我已将Custom-Filter-Header添加到此行中

config.addExposedHeader("Authorization, x-xsrf-token, Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, " +
                "Content-Type, Access-Control-Request-Method, Custom-Filter-Header");

You can replace this Custom-Filter-Header with your ReturnStatus你可以用你的ReturnStatus替换这个Custom-Filter-Header

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM