javascript - Angulars $http.post 基本原理

标签 javascript jquery angularjs

类似的 jQuery 函数

$.post("/example/handler", {foo: 1, bar: 2});

将使用 post 参数 foo=1&bar=2 创建请求。鉴于

$http.post("/example/handler", {foo : 1, bar: 2});

似乎发送了一个带有正文{"foo":1,"bar":2}POST请求,而不是form-uriencoded版本。为了获得我认为的预期行为,我需要做类似的事情

myModule.config(function ($httpProvider) {
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
    $httpProvider.defaults.transformRequest = function(data){
        return _.map(data, function (val, k) { return encodeURI(k) + "=" + encodeURI(val); }).join("&");
    }
});

在模块配置中。

任何人都可以解释 $http.post 参数处理背后的基本原理吗?是否存在我想要 Angulars 的默认行为,或者我没有看到的一些隐藏优势的情况?

最佳答案

我对HTTP协议(protocol)不太熟悉,但是POST请求通常不是用来发送内容而不是参数吗?通常情况下,我认为GET是与参数一起使用的。

我认为您应该能够向 POST 请求添加一个配置对象,并指定 params 属性:

params – {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.

所以也许这样的事情会起作用:

$http.post("/example/handler", {}, {params: {foo: 1, bar: 2} })

(上面的代码片段未经测试...我不确定语法是否正确。)

关于javascript - Angulars $http.post 基本原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14011410/

相关文章:

javascript - 自定义属性方法在 Sails js 中如何工作

javascript - 如何删除侧边栏以使网页更具响应性

Javascript 函数作用域

'memory' 中下一篇文章的 Javascript (Jquery) 代码

javascript - 尝试使用 toPrecision 时 toPrecision 不是函数

javascript - 使用 Angular 过滤器但不使用 jQuery 删除 DOM 元素

javascript - react /Dnd : Make a component draggable and droppable at the same time

javascript - jQuery 从字符串中删除字符串

javascript - AngularJS 问题不显示输出

angularjs - 在 Protractor 测试中等待服务器响应(和检查值)