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

时间:2014-12-09 09:41:58

标签: angularjs forms post ngresource

我正在尝试向服务器提交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?

4 个答案:

答案 0 :(得分:8)

默认情况下,Angular使用application / json并不足以将头设置为url encode,你必须实际转换数据,你可以通过在$ 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:我没写这个。这段代码取自了multisight的课程,名为Angular Front to Back with Web API。

答案 1 :(得分:2)

由于angularjs 1.4,您可以使用$httpParamSerializer

function transformUrlEncoded(data) {
    return $httpParamSerializer(parameters); 
}

...

$resource('http://myproj.herokuapp.com/api/signIn', {}, {
    post: {
        method: "POST",
        headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
        transformRequest: transformUrlEncoded
    }
});

答案 2 :(得分:1)

我遇到了类似的问题,AngularJS $资源服务默认以JSON格式发布数据,即如果您检查请求中的Content-type标头,则会看到Content-type: application/json

在我的情况下,我的服务器可以处理这些有效负载,但找到了Google thread可能对您的情况有所帮助。

答案 3 :(得分:0)

这是与AngularJS的Symfony表单进行通信的非常好的方式:

感谢s1moner3d提示

class AngularForm
{
constructor($scope, $http, $httpParamSerializerJQLike) {
    'ngInject';
    this.http = $http;
    this.input= '';
    this.$httpParamSerializerJQLike = $httpParamSerializerJQLike;
}

sendForm(){

    let conf = {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        url: '/api/input',
        data: this.$httpParamSerializerJQLike({'name_of_form': {'input':this.input}}),
    }

    this.http(conf).then( (response)=>{
        //success
    }, (response)=> {
        //error :(
    });

}

}