Angular 5不发送标题

时间:2018-03-21 12:44:29

标签: angular angular-httpclient

我已经浏览过很多帖子,但是在找不到get请求中传递的标题时,我找不到问题:

return this.httpClient.get(this.parseUrl(controller), {
  headers: new HttpHeaders({'Authorization': 'bearer ' + this.authService.getToken()}),
  params: this.parseURLData(data)
})
  .timeout(this.serverTimeout);

因此请求运行,添加了参数但是标题丢失了?所有我进入控制台的是:

Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:en-GB,en-US;q=0.9,en;q=0.8
Access-Control-Request-Headers:authorization
Access-Control-Request-Method:GET
Connection:keep-alive
Host:h98t5z1
Origin:http://localhost:4200
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36

我也为标题尝试了这种表示法,但仍然是空的:

let headers = new HttpHeaders().set('header1', hvalue1); 
headers = headers.append('header2', hvalue2);

的package.json

"dependencies": {
    "@angular/animations": "^5.2.0",
    "@angular/common": "^5.2.0",
    "@angular/compiler": "^5.2.0",
    "@angular/core": "^5.2.0",
    "@angular/forms": "^5.2.0",
    "@angular/http": "^5.2.0",
    "@angular/platform-browser": "^5.2.0",
    "@angular/platform-browser-dynamic": "^5.2.0",
    "@angular/router": "^5.2.0",
    "bootstrap-css-only": "^4.0.0",
    "core-js": "^2.4.1",
    "moment": "^2.17.1",
    "roboto-fontface": "^0.6.0",
    "rxjs": "^5.5.6",
    "web-animations-js": "^2.3.1",
    "zone.js": "^0.8.19"
}

请求在邮递员中起作用,因为标题存在。

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

对我来说,就像这样工作

我希望能帮助您使用此代码

public getUsers(): Observable<User[]> {

    let headers = new Headers();
    headers.append('x-access-token', this.auth.getCurrentUser().token);

    return this.http.get(Api.getUrl(Api.URLS.getUsers), {
      headers: headers
    })
      .map((response: Response) => {
        let res = response.json();

        if (res.StatusCode === 1) {
          this.auth.logout();
        } else {
          return res.StatusDescription.map(user=> {
            return new User(user);
          });
        }
      });
  }

答案 1 :(得分:0)

我在Android和Chrome应用之间切换。 Android需要我的机器名称在网络上,Chrome不能使用此功能,但可以使用localhost。更改我的URL以在Chrome中使用localhost就可以了。