javascript - 带有 json 参数的 Angular http 请求

标签 javascript json angularjs http

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

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

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

它应该看起来像这样:

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

这就是我发送 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) { .......

我在其他获取请求上执行相同的操作,但没有遇到此问题。

我在这里做错了什么吗?这与 Angular 解析参数的方式有关吗?

谢谢

最佳答案

喜欢$http docs

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.

后面的强调是我加上去的。

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

JSON.stringify(query);

所以这个

{'source': 'incident'}

转向此:

'{"source": "incident"}'

RFC 1738状态:

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

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

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

希望这有帮助!

关于javascript - 带有 json 参数的 Angular http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21753072/

相关文章:

Javascript React sessionstorage 如果登录更改导航链接

javascript - 如何为 Node.js 创建模块?

asp.net - 使用存储在客户端隐藏的大型 JSON

c# - 尝试反序列化从 Exception 继承的类时 Json.net 失败

node.js - 从 AngularJS 发布时,FormidableJS 表单不解析

javascript - 如何使用 Angular 根据选择下拉列表制作复选框值?

javascript - 我如何 console.log 数组中的每个元素?

javascript - 在页面加载时提醒/显示消息 1 次,而不是单击按钮

java.io.FileNotFoundException : File file:/data/home/test/analysis. json 不存在。读取 json 时 Spark 错误

javascript - 在 ionic 项目中注入(inject)自定义 JS 文件