【问题标题】:using angular/Http headers are not getting passed with the request使用 angular/Http 标头未随请求一起传递
【发布时间】:2017-10-31 23:31:54
【问题描述】:

我是 Angular 的新手,我正在尝试调用 REST 服务来获取将用于填写注册页面下拉列表的组织列表。我的登录页面工作正常,我得到一个令牌并将其存储在 localStorage 中。根据 console.log() 语句,在注册流程期间,也会检索此令牌,但它只是没有在请求的标头中传递。这是来自 chrome 开发工具的标题列表。 enter image description here

这是我的 http.service.ts

import {Injectable} from '@angular/core';
import {Http, Headers, RequestOptions} from '@angular/http';


@Injectable()
export class HttpService {

  constructor (public http: Http) {}

  createAuthorizationHeader(headers: Headers) {
    console.log('HttpService createAuthorizationHeader called');
    let tok = JSON.parse(localStorage.getItem('currentUser')).token;
    console.log(tok);
    //headers.append('X-Authorization', 'Bearer  ' + tok);
    headers.set('X-Authorization', 'Bearer  ' + tok);
  }

  get(url) {
    let headers = new Headers();
    console.log('HttpService get called- ' + url);
    this.createAuthorizationHeader(headers);
   /* let tok = JSON.parse(localStorage.getItem('currentUser')).token;
    console.log(tok);
    //headers.append('X-Authorization', 'Bearer  ' + tok);
    headers.set('X-Authorization', 'Bearer  ' + tok);*/

    let options = new RequestOptions({ headers: headers });

    console.log(headers.toJSON());
    return this.http.get(url, options).map(res => res.json());
  }

  post(url, data) {
    let headers = new Headers();
      this.createAuthorizationHeader(headers);
    return this.http.post(url, data, {
      headers: headers
    });
  }
}

我是这样称呼它的

import { Injectable, OnInit } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import {HttpService} from './http.service';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Organization} from '../../model';

@Injectable()
export class OrganizationService implements OnInit {
  orgs: Organization[];
  constructor(private http: HttpService) { this.http = http}
  ngOnInit() {
    console.log('ngOnInit OrganizationService called.');
  }
  getOrganizations(): any {
    console.log('getOrganizations OrganizationService called.');
    // get the token here from localstorage and add to header.
     return  this.http.get('http://localhost:9966/api/getOrganizations')
      .subscribe(result => {
        console.log( result );
    });
     /* .map((res) => {
      console.log('got http response');
      console.log(res.json());
      return res.json();
    } );*/

      //return this.orgs;
  }
}

问题是“X-Authorization”标头值未随请求一起传递。这就是服务器发回 401 状态的原因。我也尝试使用 RequestOptions ,仍然是同样的问题。感谢您对此的任何帮助

【问题讨论】:

    标签: angular


    【解决方案1】:

    您正在使用 RequestOptions,但 get-method 需要 RequestOptionsArgs。只需将您的代码更改为:

    get(url) {
        let headers = new Headers();
        this.createAuthorizationHeader(headers);
    
        let options = { headers: headers }; // HERE
        return this.http.get(url, options)
           .map(res => res.json());
    }
    

    【讨论】:

    • 感谢您的建议,试过了,但还是同样的问题。
    【解决方案2】:

    重写答案以适合您的结构。

    HttpService:

    import { Injectable } from '@angular/core';
    import { Http, Headers, RequestOptions } from '@angular/http';
    import 'rxjs/add/operator/map';
    import { Observable } from "rxjs/Observable";
    
    @Injectable()
    export class HttpService {
    
      constructor(private http: Http) { }
    
      createAuthorizationHeader(): Headers {
        let tok = 'My token';
        return new Headers({ 'X-Authorization': `Bearer ${tok}` })
      }
    
      get(url): Observable<any> {
        return this.http.get(url, { headers: this.createAuthorizationHeader() }).map(res => res.json());
      }
    }
    

    组织服务

    import { Observable } from "rxjs/Observable";
    import { Injectable } from '@angular/core';
    import { RequestOptions } from '@angular/http';
    import 'rxjs/add/operator/map';
    import { HttpService } from './http.service';
    
    @Injectable()
    export class OrganizationService {
    
      constructor(private httpService: HttpService) { }
    
      getOrganisations(): Observable<any> {
        return this.httpService.get('/api/organizations');
      }
    }
    

    注册组件

    import { Component, OnInit } from '@angular/core';
    import { OrganizationService } from '../organization.service';
    
    @Component({
      selector: 'app-signup',
      templateUrl: './signup.component.html',
      styleUrls: ['./signup.component.css']
    })
    export class SignupComponent implements OnInit {
    
      constructor(private orgranizationService: OrganizationService) { }
    
      ngOnInit() {
        this.orgranizationService.getOrganisations().subscribe(resp =>
          console.log(resp));
      }
    }
    

    请求:

    【讨论】:

    • @LL,似乎我添加的任何标题都在“Access-Control-Request-Headers”下。查看开发工具输出。 “选项 /api/getOrganizations HTTP/1.1 主机:本地主机:9966 连接:保持活动缓存控制:max-age=0 访问控制请求方法:GET 来源:localhost:4200 访问控制请求标头: content-type,x-authorization Accept: / Referer: localhost:4200/signup Accept-Encoding: gzip, deflate, sdch, br Accept-Language: en-US,en;q=0.8"
    【解决方案3】:

    感谢 Markus 和 LLL 的帮助。我想我知道发生了什么。 ts CORS 在行动。 我使用 Chrome 进行测试,并且 Chrome 更安全,发送一个飞行前 OPTIONS 请求,其中不包含我添加的标头。我不得不通过不响应 401 来处理服务器端的 OPTIONS 请求。现在 Chrome 正在发送第二个请求(在 OPTIONS 成功之后),带有正确的标头。

    来自 IE 的测试在我原来的服务器端代码上运行良好。 :)

    【讨论】:

      猜你喜欢
      • 2016-12-11
      • 2016-11-13
      • 1970-01-01
      • 1970-01-01
      • 2020-01-22
      • 1970-01-01
      • 1970-01-01
      • 2017-11-20
      • 2017-06-01
      相关资源
      最近更新 更多