how to send x-www-form-urlencoded data using ngResource module with angular?

£可爱£侵袭症+ 提交于 2019-12-10 10:19:08

问题


everything lives in the title.

when producing a resource in angular :

myModule.factory('MyResource', ['$resource', function ($resource) {

    return $resource('api/MyResource/:id');

}]);

and using in a controller :

MyResource.save({att: att, att2: att2});

the Service sends the data in a json artifact ahead to the server.

I need to send the data in a x-www-form-urlencoded shape.

Where ought I modify my code to resolve that ?


回答1:


Should pass the headers parameters

myModule.factory('MyResource', ['$resource', function ($resource) {
    return $resource('api/MyResource/:id', {}, {
        save: {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }
    });
}]);

then serialize your data before sending them with $httpParamSerializer

myModule.controller('appController', function ($httpParamSerializer) {
    MyResource.save($httpParamSerializer({att: att, att2: att2}));
}



回答2:


Complete answer (since angular 1.4). You need to include de dependency $httpParamSerializer

var res = $resource(serverUrl + 'Token', { }, {
                save: { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
            });

            res.save({ }, $httpParamSerializer({ param1: 'sdsd', param2: 'sdsd' }), function (response) {

            }, function (error) { 

            });



回答3:


I finally found myself:

When defining a resource and the associated instruction, the "headers" parameter comes in hand.

myModule.factory('MyResource', ['$resource', function ($resource) {

    return $resource('api/MyResource/:id', {}, {
      save: { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
    });

}]);


来源:https://stackoverflow.com/questions/29149786/how-to-send-x-www-form-urlencoded-data-using-ngresource-module-with-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!