簡體   English   中英

angular http 在請求中獲取發送正文參數為 json

[英]angular http get send body params as json in request

我試圖在 angular 中提出這個請求:

curl --location --request GET 'http://localhost:5000/location/searchDistanceAndTags?pageNo=1&size=1' \
--header 'token: $IKFASOmV#*+JIL4X0FGTDZNRPB3GN7HvAB9QD2X8QWeLsqtKW1U5YHnxCMRywEbUZlu??oz!!!!6r' \
--header 'Content-Type: application/json' \
--data-raw '{
"lat": "38.8993487",
"lng": "-77.0145665",
"radius": "100",
"tags": ["bier"]
}'

這是我在 angular 中的代碼,不幸的是沒有設置參數(后端在 req.body 中沒有收到任何數據)

 const dataset = {
  lat: '38.8993487',
  lng: '-77.0145665',
  radius: '100',
  tags: ['bier']
};

return this._httpClient.get<any>(`http://localhost:5000/location/searchDistanceAndTags?pageNo=${this.pageNumber}&size=10`, {
  headers: {token: this.apikey,
    'Content-Type':  'application/json'},
  params: dataset
});

盡管 GET 請求在技術上可以有一個像這個SO answer中所示的主體,但實際上支持它的庫並不多。 正如您所指出的,CURL 確實如此。 但是,像 fetch、Xhr (XmlHttpRequest) 這樣的前端 API 不允許在 GET 請求中發送正文。

如果我沒記錯的話,Angular 的HttpClient使用 Xhr,所以你不會被允許這樣做。

您可以修改 API 以改為接受發布請求,或接受查詢字符串中的參數

參數可以通過 HttpParams 發送:

const params = new HttpParams()
   .set('lat', 'one!')
   .set('lng', "two");  // and so on

可以通過以下方式創建標頭:

const headers = new HttpHeaders()
        .set("X-CustomHeader", "custom header value");

this.httpClient.get<any>(yoururl,{params}) // {params} short form of {params:params}
or:
this.httpClient.get<any>(yoururl,{headers: headers, params: params})

暫無
暫無

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

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