Angular http.get headers 未被识别

Angular http.get headers not being recognized

我正在构建一个 angular 6 应用程序,它通过 REST API 向服务器发送 get 请求。 URL 接受一些 header 和 returns 所需的数据,并已在 PostMan 上成功测试。这是显示服务器所需 headers 的屏幕截图:

我正在尝试使用 http.get 创建一个函数,以便在我的应用程序中检索这些记录。我已经创建了一个名为 listService 的服务,它将接受模块名称并准备一个 header object。然后该服务将调用 adapterService(包含我的 get 函数),它会准备 header 并向服务器发出请求。不幸的是,我没有得到有效的回复,而是收到以下错误:

"SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:13170:51) at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:2743:31) at Object.onInvokeTask (http://localhost:4200/vendor.js:42628:33) at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:2742:36) at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (http://localhost:4200/polyfills.js:2510:47) at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.js:2818:34) at invokeTask (http://localhost:4200/polyfills.js:3862:14) at XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.js:3888:17)"

从服务器添加日志后,我注意到请求中发送了 headers:

 Wed Mar 20 11:37:43 2019 [21570][-none-][FATAL] Array
(
    [Host] => localhost
    [Connection] => keep-alive
    [Accept] => application/json, text/plain, */*
    [Origin] => http://evil.com/
    [User-Agent] => Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36
    [Referer] => http://localhost:4200/profile
    [Accept-Encoding] => gzip, deflate, br
    [Accept-Language] => en-US,en;q=0.9
    [If-None-Match] => d41d8cd98f00b204e9800998ecf8427e
)

我发送的数据甚至没有添加到 header 中!我不确定为什么会这样。我已经检查了文档,看看我是否以错误的方式添加了 http headers,并在各个点记录了控制台,一切似乎都很好 直到 调用至 http.get。我真的不明白这是怎么回事。

这是我的代码:

listService

import { Injectable } from '@angular/core';
import { JwtService } from 'src/app/services/jwt/jwt.service';
import { AdapterService } from 'src/app/services/adapter/adapter.service';
import { environment } from 'src/environments/environment';
import { NGXLogger } from 'ngx-logger';
import { Observable } from 'rxjs';
import { ToastrService } from 'ngx-toastr';
import { TranslatePipe } from 'src/app/pipes/translate/translate.pipe';

/**
* This property contains the attributes of the environment configuration.
*/
const API = environment.api;

@Injectable({
  providedIn: 'root'
})
export class ListService {

  /**
  * Constructor to initialize the jwt service, adapter service, logger and translation pipe
  */
  constructor(private adapter: AdapterService,
    private jwt: JwtService,
    private translate: TranslatePipe,
    private logger: NGXLogger,
    private toaster: ToastrService) { }

  /**
   * This method initialzes the parameters for the the Get call.
   *
   * @param  username
   * @param  password
   * @return
   */
  initializeParameters(module: string): any {
    let token = this.jwt.getToken();
    let params = {
      "module": module,
      "platform": API.platform,
      "oauth_token": token
    };
    return params;
  }

  /**
  * This method sends request for listing relevant data from module
  */
  listData(module: string) {
    let params = this.initializeParameters(module);
    this.adapter.get('customPortalApi/listRecords', params)
      .subscribe(
        response => {
          this.logger.warn(response);
        },
        error => {
          let errmsg = this.translate.transform("pages[login_page][responses][error][" + error.error + "]");
          this.toaster.error(errmsg); console.log(error);
        }
      )
  }
}

adapterService(header 和获取函数)

private requestHeaders(path: string, headerData: any) {
    let headers;
    if (path !== 'customPortalApi/customToken') {
        headers = new HttpHeaders();
        for(let key in headerData){
          let value = headerData[key];
          headers = headers.append(key, value);
        }
      }
        return headers;
    }

  /**
   * This method generates the GET api call.
   *
   * @param path
   * @param params
   * @method get
   * @return
   */
    get(path: string, data: any, params: HttpParams = new HttpParams()): Observable < any > {
    let headers = this.requestHeaders(path, data); 
    return this.http.get(`${API_URL}${path}`, headers)
            .pipe(catchError(this.formatErrors));
    }

虚拟组件(调用)

import { Component, OnInit } from '@angular/core';
import {ListService} from 'src/app/services/list/list.service';

/**
* This component is for testing
*/
@Component({
  selector: 'app-dummy',
  templateUrl: './dummy.component.html',
  styleUrls: ['./dummy.component.scss']
})
export class DummyComponent implements OnInit{
  constructor(private list: ListService){}

  ngOnInit(){
    this.list.listData("accounts");
  }
}

EDIT 对于任何想在调用 http.get 之前了解 header object 的样子的人:

另一个编辑 可能是 CORS 导致了问题吗?我已将 Access-Control-Allow-Origin 设置为“*”。这是我的网络 activity 一旦我提出更改建议:

REST 服务正在被攻击,但它没有将我重定向到我的 API

当我通过邮递员发送时,服务器上记录的 header 是:

Wed Mar 20 12:52:50 2019 [21570][1][FATAL] Array
(
    [Host] => localhost
    [Connection] => keep-alive
    [module] => Accounts
    [Cache-Control] => no-cache
    [oauth_token] => 9efe19d4d2ec3b557b4d0588a3f74d5d3cc0ed46
    [platform] => base
    [User-Agent] => Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36
    [Postman-Token] => 3ddc88e1-e7a8-700f-580b-801da5f0adde
    [Accept] => */*
    [Accept-Encoding] => gzip, deflate, br
    [Accept-Language] => en-US,en;q=0.9
    [Cookie] => download_token_base=e790d5a8-17a4-4110-98ab-a6648a0ef385
)

这些工作正常

get(path: string, data: any, params: HttpParams = new HttpParams()): Observable < any > {
let httpOptions ={headers: this.requestHeaders(path, data)}; 
return this.http.get(`${API_URL}${path}`, httpOptions)
        .pipe(catchError(this.formatErrors));
}

像这样尝试。您需要传递一个包含 headers 属性.

的选项 object

https://angular.io/guide/http#adding-headers