gpt4 book ai didi

angularjs - 如何使用Angular $ resource发送x-www-form-urlencoded数据?

转载 作者:行者123 更新时间:2023-12-04 13:49:45 24 4
gpt4 key购买 nike

我正在尝试向服务器提交POST请求,该服务器仅接受x-www-form-urlencoded格式的数据。

当我在Postman上进行测试时,它可以工作。例如,预览标题如下所示:

    POST /api/signin HTTP/1.1
Host: myproj.herokuapp.com
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded

email=joe%40gmail.com&password=1234567

但是,当我从应用程序运行它时,在Chrome控制台中查看的标题看起来像:
    Remote Address:10.10.10.250:80
Request URL:http://myproj.herokuapp.com/api/signIn
Request Method:POST
Status Code:400 Bad Request
Request Headersview source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:53
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:rapidit.herokuapp.com
Origin:http://localhost
Referer:http://localhost/rapid/v3/src/app/index/
User-Agent:Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36
Form Dataview parsed
{"email":"joe@gmail.com","password":"1234567"}

显然,它没有以正确的格式发送数据。

这是我的Angular工厂中的外观(带有硬编码的登录数据):
var LoginResource = $resource("http://myproj.herokuapp.com/api/signIn", {}, {
post: {
method: "POST",
isArray: false,
headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
}
});
var loginUser = function (){
return LoginResource.post(
{
email: "joe@gmail.com",
password: "1234567"
}
).$promise; //this promise will be fulfilled when the response is retrieved for this call
};
return loginUser;

如何获取所需格式的数据到POST?

最佳答案

默认情况下,Angular使用application/json,并且仅设置标题以进行url编码是不够的,您必须实际转换数据,可以通过在$ resource服务上使用de transformRequest选项来实现。这就是它的样子。

angular.module("AuthModule")
.factory("authResource", ['$resource', 'appSettings', function ($resource, appSettings) {

return {
login: $resource(appSettings.serverPath + '/Token', null,
{
loginUser: {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function (data, headersGetter) {
var str = [];
for (var d in data)
str.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
return str.join("&");
}
},
})
}

}]);

P/D:我没有写这个。这段代码取材于称为Angular Front to Back with Web API的复数类(class)。

关于angularjs - 如何使用Angular $ resource发送x-www-form-urlencoded数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27375710/

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