Angular http.get标头无法识别

时间:2019-03-20 06:50:18

标签: angular typescript rest sugarcrm

我正在构建一个有角度的6应用程序,该应用程序通过get向服务器发送REST API请求。该URL带有几个标头并返回所需的数据,并且已经在PostMan上成功进行了测试。这是显示服务器所需标题的屏幕截图:

Post Man image

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

  

“ SyntaxError:JSON中位置0处的意外令牌<       在JSON.parse()       在XMLHttpRequest.onLoad(http://localhost:4200/vendor.js:13170:51)       在ZoneDelegate.push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.invokeTask(http://localhost:4200/polyfills.js:2743:31)       在Object.onInvokeTask(http://localhost:4200/vendor.js:42628:33)       在ZoneDelegate.push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.invokeTask(http://localhost:4200/polyfills.js:2742:36)       在Zone.push ../ node_modules / zone.js / dist / zone.js.Zone.runTask(http://localhost:4200/polyfills.js:2510:47)       在ZoneTask.push ../ node_modules / zone.js / dist / zone.js.ZoneTask.invokeTask上[作为调用](http://localhost:4200/polyfills.js:2818:34)       在invokeTask(http://localhost:4200/polyfills.js:3862:14)       在XMLHttpRequest.globalZoneAwareCallback(http://localhost:4200/polyfills.js:3888:17)”

添加来自服务器的日志后,我注意到请求中正在发送的标头:

 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
)

我发送的数据甚至都没有添加到标题中!我不确定为什么会这样。我检查了一下文档,看看是否以错误的方式添加了http headers,并在各个位置记录了控制台,并且在向上调用{{ 1}}。我真的不明白这里发生了什么。

这是我的代码:

listService

http.get

adapterService(标题和获取功能)

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);
        }
      )
  }
}

虚拟组件(用于通话)

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"); } } 之前了解标头对象的外观的人:

picture

另一个编辑 可能是CORS引起了问题吗?我已将http.get设置为“ *”。提出更改后,这是我的网络活动:

result

Access-Control-Allow-Origin服务被击中,但没有将我重定向到我的API

我通过邮递员发送时在服务器上记录的标头是:

REST

这些正常正常工作

1 个答案:

答案 0 :(得分:1)

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属性的选项对象。

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