簡體   English   中英

無法識別 Angular http.get 標頭

[英]Angular http.get headers not being recognized

我正在構建一個 angular 6 應用程序,它通過REST API向服務器發送一個get請求。 該 URL 接受一些標頭並返回所需的數據,並已在 PostMan 上成功測試。 這是顯示服務器所需標頭的屏幕截圖:

郵遞員圖片

我正在嘗試使用http.get創建一個函數,以便在我的應用程序中檢索這些記錄。 我創建了一個名為listService的服務,它將接收模塊名稱並准備一個標頭對象。 然后該服務將調用一個adapterService (包含我的get函數),它將准備標頭並將請求發送到服務器。 不幸的是,我沒有得到有效的響應,而是收到以下錯誤:

“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 ) 在 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 [as invoke] ( 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 ,並在各個點記錄了控制台,一切似乎都很好,直到調用http.get 我真的不明白這里發生了什么。

這是我的代碼:

列表服務

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(標頭和獲取功能)

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

編輯的人誰想要得到的標題對象的外觀進行調用之前怎么樣的想法http.get

圖片

另一個編輯難道是 CORS 可能導致問題? 我已將Access-Control-Allow-Origin為“*”。 這是我提出更改后的網絡活動:

結果

REST服務受到攻擊,但它沒有將我重定向到我的 API

當我通過郵遞員發送時,服務器上記錄的標頭是:

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 屬性的選項對象。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM