angularjs - pyramid not work with angular $http post -
$http({method: 'post', url: 'http://localhost:5001/products', data: {token: $scope.product.token}}).success( function () { alert('success'); } );
in pyramid side, request.post show novars: not form request. not html form submission( content-type: application/json)
i using cornice provide api(/products) , thinks pyramid's problem.
does have solution?
angular sends post body (data) application/json
while forms sent application/x-www-form-urlencoded
. pyramid parses body , let access in request.post
when it's encoded normal form.
it not possible represent every data encoded angular way (json) key/value pair provided pyramid api.
[ 1, 2, 3, 4 ]
solution on pyramid side
it can solved per view or globally
per view
this pyramid way , flexible way handle this.
@view_config(renderer='json') def myview(request): data = request.json_body # deal data. return { "success" : true }
globally
pyramid can set assume body encoded application/json
object , properties put in request.post.
solution on angular side
as pyramid side, can solved per request , globally.
per request
you need send data way forms sent:
$http({ method: 'post', url: url, headers: {'content-type': 'application/x-www-form-urlencoded'}, transformrequest: function(obj) { var str = []; for(var p in obj) { if (obj.hasownproperty(p)) { str.push(encodeuricomponent(p) + "=" + encodeuricomponent(obj[p])); } } return str.join("&"); }, data: xsrf }).success(function () {});
globally
to send posts form default, configure $httpprovider so.
angular.module('httppostasform', []) .config(['$httpprovider', function ($httpprovider) { $httpprovider.defaults.headers.post["content-type"] = "application/x-www-form-urlencoded"; $httpprovider.defaults.transformrequest.unshift(function (obj) { var str = []; for(var p in obj) { if (obj.hasownproperty(p)) { str.push(encodeuricomponent(p) + "=" + encodeuricomponent(obj[p])); } } return str.join("&"); }); }]);
then include module in app:
angular.module("app", ["httppostasform"]);
Comments
Post a Comment