【问题标题】:angular http get send body params as json in requestangular http get 在请求中将正文参数作为 json 发送
【发布时间】:2020-05-25 04:40:56
【问题描述】:

我正在尝试以角度提出此请求:

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 方法从正文发送

标签: angular httpclient


【解决方案1】:

尽管 GET 请求在技术上可以具有像 SO answer 中所示的主体,但实际上支持它的库并不多。正如您所指出的,CURL 确实如此。但是,fetch、Xhr (XmlHttpRequest) 等前端 API 不允许在 GET 请求中发送正文。

如果我没记错的话,Angular 的 HttpClient 使用 Xhr,所以你不会被允许这样做。

您可以修改您的 API 以改为接受发布请求,或接受查询字符串中的参数

【讨论】:

    【解决方案2】:

    可以通过 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})
    

    【讨论】:

      猜你喜欢
      • 2019-08-15
      • 2021-02-17
      • 2017-06-23
      • 2019-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      • 1970-01-01
      相关资源
      最近更新 更多