【问题标题】:How to pass multiple parameters in http GET request in Angular?如何在Angular的http GET请求中传递多个参数?
【发布时间】:2020-09-11 09:55:46
【问题描述】:

我正在使用以下方法在 http get 请求中传递多个参数,但它给了我一个错误 -

import { HttpParams, HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) { }

let params = new HttpParams();
params = params.append('var1', val1);
params = params.append('var2', val2);

this.http.get(StaticSettings.BASE_URL, {params: params}).subscribe(...);

错误 - 无法重新声明块范围变量“params”

如果我更改名称,那么如何在 URL 中调用它?

作为一种解决方法,我想到了直接在 URL 中附加参数,而不是如下-

this.params1 = 'parameter1';
this.params2 = 'parameter2';
this.params3 = 'parameter3';

http 请求 -

return this.http.get('URL/json?'+'&parameter1='+this.params1+'&parameter2='+this.params2+'&parameter3='+this.params3)

我收到了这个错误 -

Access to XMLHttpRequest at 'URL/json?'+'&parameter1='+this.params1+'&parameter2='+this.params2+'&parameter3='+this.params3' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

为了检查 URL 是否正确附加,我点击了错误中的 url,它工作正常。

谁能帮我解决这个问题?

谢谢!!

【问题讨论】:

  • &parameter1: 第一个 & 符号太多,但这不是问题。

标签: angular xmlhttprequest


【解决方案1】:

可以发送参数:

const params = new HttpParams()
   .set('p1', 'one!')
   .set('para2', "two");

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

你的代码看起来不错,也许你有一个cors问题:什么是StaticSettings.BASE_URL? http 还是 https?还是相对网址?

【讨论】:

  • 太好了!谢谢!它正确附加了所有参数,但我仍然收到 CORS 错误。我该如何解决这个问题?
  • 这是第二个问题 ;-) 好的。我需要信息:什么是 StaticSettings.BASE_URL? http 还是 https?还是相对网址?
  • 已经解决了!!找到了解决方案!不管怎么说,多谢拉 !!我正在向 Google Places API 发出请求
【解决方案2】:

问题的第一部分(即传递多个参数)已解决。感谢@Marc 回答了这个问题。

我认为问题出在我附加参数的方式上,但这是一个 CORS 问题。为了解决这个问题,我在 http 请求中的 url 之前添加了 https://cors-anywhere.herokuapp.com 作为 -

https://cors-anywhere.herokuapp.com/URL 成功了! :)

【讨论】:

    猜你喜欢
    • 2016-01-25
    • 2020-08-20
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    • 2014-12-21
    • 1970-01-01
    • 2020-02-25
    相关资源
    最近更新 更多