javascript 带有 json 参数的 Angular http 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21753072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:36:35  来源:igfitidea点击:

Angular http request with json param

javascriptjsonangularjshttp

提问by Sherlock

In my RESTful api one of the resources exposes a GET method that accept json as a parameter named 'query'. This parameter is passed directly to the MongoDB query allowing users to query the database directly using mongo syntax.

在我的 RESTful api 中,其中一个资源公开了一个 GET 方法,该方法接受 json 作为名为“查询”的参数。此参数直接传递给 MongoDB 查询,允许用户使用 mongo 语法直接查询数据库。

The problem I'm having is that the request always looks like this:

我遇到的问题是请求总是如下所示:

?&query=%7B%22source%22:%22incident%22%7D 

Where it should look something like this:

它应该看起来像这样:

?&query={'source': 'incident'} 

This is how I am sending the GET request:

这就是我发送 GET 请求的方式:

var query = {};
if ($scope.sourceFilter) { query.source = $scope.sourceFilter; }
    var query = JSON.stringify(query);
    $http.get('/api/feedbackEntries', {params: {limit: $scope.limit, query: query}}).success(function(data) { .......

I am doing the same thing on other get requests and I don't get this issue.

我正在对其他 get 请求做同样的事情,但我没有遇到这个问题。

Am I doing something wrong here ? Is this to do with the way angular parses params ?

我在这里做错了吗?这与 angular 解析 params 的方式有关吗?

Thanks

谢谢

采纳答案by Sherlock

After some digging I figured this one out. Looking at the request I was making:

经过一番挖掘,我想出了这个。查看我提出的请求:

$http.get('/api/feedbackEntries',

I saw that the url does not end with a trailing slash. This was the only difference I could see compared with other requests that were working fine. So I added the trailing slash and magically it works. I can't explain why, whether it's something within angular or elsewhere .. but this is how I fixed the problem.

我看到 url 没有以斜杠结尾。与其他工作正常的请求相比,这是我能看到的唯一区别。所以我添加了尾部斜杠,它神奇地起作用了。我无法解释为什么,无论是角度内还是其他地方..但这就是我解决问题的方式。

Hope this helps someone in the future.

希望这对将来的人有所帮助。

回答by jakee

Like the $httpdocssay

就像$http文档说的

params{Object.<string|Object>}– Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified.

params{Object.<string|Object>}– 字符串或对象的映射,将在 url 之后转换为 ?key1=value1&key2=value2。如果该值不是字符串,它将被 JSON 化。

Latter emphasis is added by me.

后面的重点是我加的。

So the queryproperty of the object you pass to the paramsconfiguration option is an Object. This means is will be JSONified, which means the same as

所以query你传递给params配置选项的对象的属性是一个对象。这意味着将被JSON化,这意味着与

JSON.stringify(query);

So this

所以这

{'source': 'incident'}

Turns to this:

转到这个:

'{"source": "incident"}'

As RFC 1738states:

正如RFC 1738所述:

... only alphanumerics, the special characters "$-_.+!*'(),", and reserved characters used for their reserved purposes may be used unencoded within a URL.

... 只有字母数字、特殊字符 "$-_.+!*'()," 和用于其保留目的的保留字符可以在 URL 中未编码地使用。

As it happens {, }and "are not on that list and have to be url encoded to be used in a url. In your case %7Bcorresponds to {, %7Dcorresponds to }and %22corresponds to ".

碰巧{}并且"不在该列表中,必须进行 url 编码才能在 url 中使用。在您的情况下%7B对应于{%7D对应于}并且%22对应于"

So what is happening is normal and most server software automatically decodes the url query parameters for you, so they will be presented normally. Most likely you'll need to parse it back to JSON somehow!

所以发生的事情是正常的,大多数服务器软件都会自动为你解码url查询参数,所以它们会正常呈现。您很可能需要以某种方式将其解析回 JSON!

Hope this helps!

希望这可以帮助!

回答by petur

When using RESTFul apis concider using ngResource, ngResource docs

使用ngResourcengResource docs使用 RESTFul apis 时

Include it in your module:

将其包含在您的模块中:

yourApp = angular.module('yourApp', ['ngResource'])

Add your service:

添加您的服务:

yourApp.factory('YourService', ['$resource', function($resource){
return $resource('link/to/your/object', {});
}]);

Add your controller

添加您的控制器

yourApp.controller('YourController', [$scope, 
'YourService', function($scope, YourService) {

$scope.yourData = YourService.get(); 
$scope.yourData = YourService.query(); //(When obtaining arrays from JSON.)

I've found this is the best way using a RESTFull api.

我发现这是使用 RESTFull api 的最佳方式。

回答by Romanyu

Below is the code I used to get search result from my server, it works for me sending POST request with JSON params without .

下面是我用来从我的服务器获取搜索结果的代码,它适用于我发送带有 JSON 参数的 POST 请求而没有 .

var service = {
  getResult: function ({"username": "roman", "gender": "male"}) {

    var promise = $http({
      url: ServerManager.getServerUrl(),
      method: "POST",
      data: params,
      headers: {
        'Content-Type': 'application/json'
      }
    })
      .success(function (data, status, headers, config) {
      console.log('getResult success.');
      return data;

    }).error(function (data, status) {
      console.log('getResult error.');
    });

    return promise;
  }
}
return service;