标头被传递为空吗?

时间:2019-07-12 13:29:54

标签: angular get http-headers

我正在创建一个Web服务来托管使用Angular的API。我正在发送GET请求,但始终收到以下错误:

HttpErrorResponse {headers: HttpHeaders, status: 500, statusText: "Internal Server Error"

当我检查后端时,是因为标头以null传递。

我在Chrome上有一个跨源扩展程序。我使用邮递员检查后端是否正常工作,并且标头运行正常。是我的Angular应用程序导致了null标头。我有以下方法:

get_url(){
  let headers: HttpHeaders = new HttpHeaders();

  headers.append('fsreqid','test');
  headers.append('Authorization', 'Bearer 4Agl9Gd75LHEvOmXqKoZh4oUlxjqZs4Tg6dF8vcx7qymwjE8ni5gT8');
  headers.append('Access-Control-Allow-Origin', '*');

  return this.http
    .get(this.url, { headers: headers })
    .subscribe((res: HttpResponse<any>) => {
      observe: 'response' 
      ResponseType: 'json'
  })

2 个答案:

答案 0 :(得分:0)

请尝试使用

headers = new HttpHeaders();
headers.set('fsreqid','test');
headers.set('Authorization', 'Bearer 4Agl9Gd75LHEvOmXqKoZh4oUlxjqZs4Tg6dF8vcx7qymwjE8ni5gT8');
headers.set('Access-Control-Allow-Origin', '*');

答案 1 :(得分:0)

append()不会修改输入标题,因此您必须重新分配标题:

 let headers: HttpHeaders = new HttpHeaders();

 headers = headers.append('fsreqid','test');
 headers = headers.append('Authorization', 'Bearer 4Agl9Gd75LHEvOmXqKoZh4oUlxjqZs4Tg6dF8vcx7qymwjE8ni5gT8');
 headers = headers.append('Access-Control-Allow-Origin', '*');

或在构造函数中设置所有附加项:

  let headers: HttpHeaders = new HttpHeaders()
        .append('fsreqid','test')
        .append('Authorization', 'Bearer 4Agl9Gd75LHEvOmXqKoZh4oUlxjqZs4Tg6dF8vcx7qymwjE8ni5gT8')
        .append('Access-Control-Allow-Origin', '*');