pyramid not work with angular $http post - angularjs

$http({method: 'POST', url: 'http://localhost:5001/products', data: {token: $scope.product.token}}).success(
function () {
alert('success');
}
);
In the pyramid side, request.POST show that NOVars: Not a form request. Not an HTML form submission( Content-Type: application/json)
I am using cornice to provide my api(/products) and I thinks it is pyramid's problem.
Does anyone have a solution?

Angular sends the post body (data) as application/json while forms are normally sent as application/x-www-form-urlencoded. Pyramid parses the body and let you access it in request.POST when it's encoded as a normal form.
It is not be possible to represent every data encoded the Angular way (json) as a key/value pair like is provided by pyramid API.
[
1,
2,
3,
4
]
Solution on Pyramid side
It can be solved per view or globally
Per view
This is the pyramid way and the most flexible way to handle this.
#view_config(renderer='json')
def myview(request):
data = request.json_body
# deal with data.
return {
"success" : True
}
Globally
Pyramid can most likely be set to assume a body encoded as application/json is an object and its properties be put in request.POST.
Solution on Angular side
As with the pyramid side, it can be solved per request and globally.
Per request
You need to send the data the way forms are normally 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 as form by default, configure the $httpProvider to do 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 this module in your app:
angular.module("app", ["httpPostAsForm"]);

AngularJS $http.post is different from jquery's. The data you pass is not posted as a form but as json in the request body. So your pyramid view can not decode it as usual. You have to either:
directly access the request body and decode it in your pyramid view;
or modify your angularjs code to post your data as form content : see this other question in stackoverflow

the answer is angular $post do OPTIONS request first and then do the POST request, get data form the request.json_body

Use req.json_body if you post some json-decoded content. req.GET, req.POST, req.params only cope with from submissions. Btw, $http -> ngResource -> restangular ...

Try setting contenttype in $http, something like below.
$http(
{
url: url,
contentType: "application/json",
data: data,
method: method
})
.success(function (response) {
successcb(response);
}).error(function (data, status, headers, config) { errorcb(data); });
};

You can simply get the POST data this way:
query = json.loads(request.body)

Related

how to receive array data in ajax request page wordpress

I am sending array to PHP through angularJs $http, but when I receiving data it was showing null, I don't know is that my procedure is correct or not,
js file is
var newdisable_comments_on_post_types = JSON.stringify(allTabData.disable_comments_on_post_types);
$http({
method:'post',
url:url,
params:{
'disable_comments_on_post_types': newdisable_comments_on_post_types
}
});
while sending in the header it sending like this
disable_comments_on_post_types:{"post":false,"page":false,"attachment":false}
in the PHP file, i did some of the procedure to receive it
$a = $_POST['disable_comments_on_post_types']['post'];// method 1
$a = $_POST['disable_comments_on_post_types'] // method 2
$x=1
foreach($a as $val){
$b[$x]=$val;
$x++;
}
$a = $_POST['disable_comments_on_post_types']->post;// method 3
I am getting null in response every method while I returning data to check
echo json_encode($a);
am I doing any wrong or in WordPress we cant send an array to PHP?
Change Your $http service to this:
By default, the $http service will transform the outgoing request by
serializing the data as JSON and then posting it with the content-
type, "application/json"
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: allTabData.disable_comments_on_post_types
}).success(function () {});

What is type of data angular sending?

What is type of data angular sending? I use laravel + angular. I`m trying, but this script return 405 error. Method not allowed.
.controller('adminCtrl', function( $scope, $http ){
$scope.collection = [];
$scope.newData = [];
$scope.newrecord = function() {
$scope.collection.push($scope.newData);
$http({
url: '/newrecord',
method: "POST",
data: $.param($scope.collection),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(function(data){
console.log(data);
})
}
})
You are getting 405 - Method not Allowed because the server you are sending your request does not have POST it the white list of methods allowed to be used to perform requests to that given API.
It's not an angularJS issue, it's a server configuration issue.
$http sends data as json.
You do not need to serialize params using "$.param", data is plain javascript object, which is send to your REST endpoint.
So attach just "$scope.collection) and do not set Content Type manually, it is json by default.
POST can be send also with convenience method.
$http.post('/someUrl', data, config).then(successCallback, errorCallback);

Angular http call fails with content-type json

Here is my service:
home.factory("homeService", function ($http, $q) {
var service =
{
getAssets: function () {
var deferred = $q.defer();
var response = $http({
method: "post",
dataType: "json",
data: '',
headers: {
'Content-Type': "application/json"
},
url: "http://localhost/myWeb/services/reports_ws.asmx/getData",
});
response.success(function (data) {
deferred.resolve(data);
});
response.error(function (data) {
alert('Error');
});
// Return the promise to the controller
return deferred.promise;
},
}
return service;
I am getting 500 error from the server when I use application/json for the content. using plain/text works fine and data is returned, but in an xml format although the server sends data back in json format. I have tested it in Chrome, everything works fine. I also noticed that Chrome sends request using "application/x-www-form-urlencoded" for content-type. I tried it too, but still got data in xml. Please help.
Thanks
keep trying with the following:
header: { "Content-Type" : "application/x-www-form-urlencoded"}
Please notice that this applies only for the header of the request, not the response. The response depends on your backend (server side).
Several ways are available to return JSON data in the response depending of the type of server you are using.

AngularJS jsfiddle $http echo not returning data

I encountered a bug in a square-connect API wrapper for node, and I made a fiddle to recreate the issue. I noticed my code wasn't working, in the sense that angular {{}} stuff isn't showing up. What's wrong with it?
the only thing I'm trying to do is have the raw JSON object (preferably {{res}}, but it doesn't matter really) shown below the create button. I am just trying to demonstrate to the author of a library that my object and data is valid, and that a bug is in his library, not my implementation.
var httpRequest = $http({
method: 'POST',
url: '/echo/json/',
data: item
}).success(function(data, status) {
$scope.res = data;
}).failure(function(data, status){
$scope.res = data+status;
});
data is not being returned from jsfiddle's ECHO.
http://jsfiddle.net/efjytg6r/2/
You were close, but since you're saving your $http in a variable, you access the methods within it using that variable. (ie: httpRequest.success / etc)
Also it's .error() not .failure()
var httpRequest = $http({
method: 'POST',
url: '/echo/json/',
data: item
});
httpRequest.success(function(data, status) {
$scope.res = data;
});
httpRequest.error(function(data, status){
$scope.res = data+status;
});
jsFiddle is finicy with it's echo AJAX examples. You need to format what you send to them correctly with json, have it stringified as well as use jQuery's $.param (since angular doesn't do POST like you're used to with jQuery).
I included jQuery to the fiddle below.
I formatted the data being sent differently
I moved your {{ res }} inside of the controller area (you had it outside, which means it won't compute)
I added | json filter to {{ res | json }}
Updated jsFiddle
// the wacky format you need if you want to do fake $http to jsFiddle
// case in point, if you're trying to DEMO this, I wouldn't even bother, since it won't look like this when you actually use this within your application
var data = $.param({
json: JSON.stringify({
item
})
});
$http.post("/echo/json/", data)
.success(function(data, status) {
$scope.res = data;
}).error(function (status) {
});
Here is an example using $httpParamSerializer and a delay.
angular.module('myApp',[]);
angular.module('myApp').controller('myVm',
function($scope,$http,$httpParamSerializer) {
var vm = $scope;
var xitem = {a:"1",b:"2"};
var data = $httpParamSerializer({
json: xitem,
delay: 6
});
console.log("Posting xitem");
vm.p = $http.post('/echo/json/',data);
vm.p.then (function(response) {
console.log(response);
console.log(response.data)
})
});

Slim, Postman and AngularJs : $app->request->getBody() vs $app->request->post()

I'm a beginner. I've written a test application made of an AngularJs GUI on the client side and a PHP API on the server side.
This is the angular service handling the requests
myApp.factory('Book', ['$resource', 'API_URL', function($resource, API_URL){
return $resource(API_URL + '/books/:bookId', {bookId: '#bookId'}, {
get: { method: 'GET', isArray:true },
update: { method: 'PUT'},
save: { method: 'POST'},
delete: {method:'DELETE'},
});
}]);
When I submit a book from the Angular app I can catch the POST in Slim by using
$post_a = json_decode($app->request->getBody());
//$post_b = $app->request->post(); //this would be empty
When I use Postman and I perform a POST I can catch the POST in Slim by using
//$post_a = json_decode($app->request->getBody()); // this would be empty
$post_b = $app->request->post();
I don't get why there is this difference. Could you please explain?
Am I not meant to catch the post just with $app->request->post(); in both the cases? Why the post coming from Angular can be caught only with $app->request->getBody()?
The $app->request->post() method retrieves key/value data submitted in a application/x-www-form-urlencoded request. If the request uses a different content-type (e.g. application/json), you can retrieve the raw request body with the $app->request->getBody() method and decode it as necessary. Let me know if you have further questions.
You could still use
$post_b = $app->request->post()
in Slim.
As long as you call this REST service from html form (AngularJS) by passing the data as form value formatted instead of as JSON.
If in AngularJS you have the data in JSON format, you have to translate it first into form. Below is the example how to invoke this REST service:
Object.toparams = function ObjecttoParams(obj) {
var p = [];
for (var key in obj) {
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
};
$http({
method: 'POST',
url: url,
data: Object.toparams(myobject),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
myobject is the data in JSON format that is going to be created
Thanks Josh..Your answers works for me.
Steps to follow:
1.You need to send request in json format under raw tab like this:
{"username":"admin","password":"admin"}
2.You need to set Content-Type to application/json in the headers.
That's it and it will work.

Resources