首页 > 解决方案 > 使用参数与硬编码 URL 时来自 http.get 的不同响应

问题描述

我有一个使用Google Civic Information API拉动政府代表的功能,当我提交硬编码的 URL 时,它按预期工作,但当我尝试使用 PARAMS 传递相同的查询时只返回一个小子集。两个测试功能都得到 200 响应。

在 URL 中硬编码查询参数的函数:

$scope.submit = function() {
  $http({
    method: 'GET',
    url: 'https://www.googleapis.com/civicinfo/v2/representatives?key=my-google-api-key&address=114%20Grand%20St%20Albany%20NY%2012202&fields=officials'
  }).then(function successCallback(response) {
      // this callback will be called asynchronously
      // when the response is available
      console.log(response);
    }, function errorCallback(response) {
      // called asynchronously if an error occurs
      // or server returns response with an error status.
      console.log("it didn't work.");
    });      

};

控制台记录了 26 名官员的回应。

具有通过 PARAMS 传递的查询参数的函数:

$scope.submit = function() {
  $http({
    method: 'GET',
    url: 'https://www.googleapis.com/civicinfo/v2/representatives',
    params: {
      key: 'my-google-api-key',
      address: '114%20Grand%20St%20Albany%20NY%2012202',
      fields: 'officials'
    }
  }).then(function successCallback(response) {
      // this callback will be called asynchronously
      // when the response is available
      console.log(response);
    }, function errorCallback(response) {
      // called asynchronously if an error occurs
      // or server returns response with an error status.
      console.log("it didn't work.");
    });      

};

控制台仅记录 8 个官员。

我一直在 $http、$http.get 和 $httpParamSerializer 的 AngularJS API 引用中上下波动,但我一生都无法弄清楚我可能会丢失什么。我究竟做错了什么?

标签: angularjsparametersget

解决方案


尝试114 Grand St Albany NY 12202作为地址参数而不是114%20Grand%20St%20Albany%20NY%2012202.

它应该看起来像:

$scope.submit = function() {
  $http({
    method: 'GET',
    url: 'https://www.googleapis.com/civicinfo/v2/representatives',
    params: {
      key: 'my-google-api-key',
      address: '114 Grand St Albany NY 12202',
      fields: 'officials'
    }
  }).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
   console.log(response);
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
    console.log("it didn't work.");
  });      

};

我认为通过114%2520Grand%2520St%2520Albany%2520NY%252012202作为参数传递,它将对 URL 进行两次编码,您将丢失信息。


推荐阅读