如何使用带 angular 的 ngResource 模块发送 x-www-form-urlencoded 数据?
how to send x-www-form-urlencoded data using ngResource module with angular?
一切都在标题中。
在 angular 中生产资源时:
myModule.factory('MyResource', ['$resource', function ($resource) {
return $resource('api/MyResource/:id');
}]);
并在控制器中使用:
MyResource.save({att: att, att2: att2});
服务将 json
工件中的数据提前发送到服务器。
我需要以 x-www-form-urlencoded
形状发送数据。
我应该在哪里修改我的代码来解决这个问题?
我终于找到了自己:
定义资源和相关指令时,"headers"参数派上用场。
myModule.factory('MyResource', ['$resource', function ($resource) {
return $resource('api/MyResource/:id', {}, {
save: { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
});
}]);
完整答案(自 angular 1.4)。您需要包含 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) {
});
应传递 headers
参数
myModule.factory('MyResource', ['$resource', function ($resource) {
return $resource('api/MyResource/:id', {}, {
save: {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
});
}]);
然后在使用 $httpParamSerializer
发送之前序列化您的数据
myModule.controller('appController', function ($httpParamSerializer) {
MyResource.save($httpParamSerializer({att: att, att2: att2}));
}
一切都在标题中。
在 angular 中生产资源时:
myModule.factory('MyResource', ['$resource', function ($resource) {
return $resource('api/MyResource/:id');
}]);
并在控制器中使用:
MyResource.save({att: att, att2: att2});
服务将 json
工件中的数据提前发送到服务器。
我需要以 x-www-form-urlencoded
形状发送数据。
我应该在哪里修改我的代码来解决这个问题?
我终于找到了自己:
定义资源和相关指令时,"headers"参数派上用场。
myModule.factory('MyResource', ['$resource', function ($resource) {
return $resource('api/MyResource/:id', {}, {
save: { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
});
}]);
完整答案(自 angular 1.4)。您需要包含 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) {
});
应传递 headers
参数
myModule.factory('MyResource', ['$resource', function ($resource) {
return $resource('api/MyResource/:id', {}, {
save: {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
});
}]);
然后在使用 $httpParamSerializer
myModule.controller('appController', function ($httpParamSerializer) {
MyResource.save($httpParamSerializer({att: att, att2: att2}));
}