gpt4 book ai didi

javascript - Angularjs $http.post 原理

转载 作者:行者123 更新时间:2023-11-29 22:18:00 27 4
gpt4 key购买 nike

可比较的 jQuery 函数

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

将创建一个带有 post 参数 foo=1&bar=2 的请求。鉴于

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

似乎发送一个 POST 请求,正文 {"foo":1,"bar":2} 而不是 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 - Angularjs $http.post 原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14011410/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com