JSONP req.body is not work - json

I'm using nodejs and angular when I clicked on a button on angular side it makes a json post but I use JSONP because of crossdomain problems. When I try to get the data that I sent from client via JSONP I get something like this;
{ '{"userName": "something", "password" : "123"}': '' }
I get it from req.body on my server.js.
Here is my serverside code
app.post('/', function(req,res){
console.log("consoleeee:" + req.body);
res.end();
});
and here my client side function that works when clicked the button
function loginPageLogin(a, b, c, d, e, f, g, h, i, j) {
$.ajax
({
type: "POST",
url: 'http://localhost:777/node',
dataType: 'jsonp',
async: false,
data: '{"userName": "' + a.value + '", "password" : "' + b.value + '"}'
})
How Can I get req.body correctly? I want it as object. Thank you...

It is not possible to POST json data using the JSONP transport because JSONP requests are sent by appending a <script> tag to the body of the page, meaning post params cannot be sent, only get params. It also means that the data you are sending needs to be in key/value pairs, not JSON. It can't be synchronous either.
Therefore, You need to decide whether you want to go the JSONP route, or the JSON route with proper CORS setup. If JSONP, organize your paypload as an object, not json, and if json, modify your server to properly handle CORS by adding the CORS middleware.

You need to change data with this so it pushes an object instead a string:
$.ajax
({
type: "POST",
url: 'http://localhost:777/node',
dataType: 'json',
async: false,
data: {userName: a.value, password: b.value}
})

Related

how to process json post request with nodejs http (no express framework)? [duplicate]

Can someone explain in an easy way how to make jQuery send actual JSON instead of a query string?
$.ajax({
url : url,
dataType : 'json', // I was pretty sure this would do the trick
data : data,
type : 'POST',
complete : callback // etc
});
This will in fact convert your carefully prepared JSON to a query string. One of the annoying things is that any array: [] in your object will be converted to array[]: [], probably because of limitations of the query sting.
You need to use JSON.stringify to first serialize your object to JSON, and then specify the contentType so your server understands it's JSON. This should do the trick:
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
Note that the JSON object is natively available in browsers that support JavaScript 1.7 / ECMAScript 5 or later. If you need legacy support you can use json2.
No, the dataType option is for parsing the received data.
To post JSON, you will need to stringify it yourself via JSON.stringify and set the processData option to false.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=UTF-8",
complete: callback
});
Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.
While I know many architectures like ASP.NET MVC have built-in functionality to handle JSON.stringify as the contentType my situation is a little different so maybe this may help someone in the future. I know it would have saved me hours!
Since my http requests are being handled by a CGI API from IBM (AS400 environment) on a different subdomain these requests are cross origin, hence the jsonp. I actually send my ajax via javascript object(s). Here is an example of my ajax POST:
var data = {USER : localProfile,
INSTANCE : "HTHACKNEY",
PAGE : $('select[name="PAGE"]').val(),
TITLE : $("input[name='TITLE']").val(),
HTML : html,
STARTDATE : $("input[name='STARTDATE']").val(),
ENDDATE : $("input[name='ENDDATE']").val(),
ARCHIVE : $("input[name='ARCHIVE']").val(),
ACTIVE : $("input[name='ACTIVE']").val(),
URGENT : $("input[name='URGENT']").val(),
AUTHLST : authStr};
//console.log(data);
$.ajax({
type: "POST",
url: "http://www.domian.com/webservicepgm?callback=?",
data: data,
dataType:'jsonp'
}).
done(function(data){
//handle data.WHATEVER
});
If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"
Original post here
Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here

Post Raw Json via .submit()

How can I post username/password as Raw JSON via form.submit().
loginForm.submit({
url: 'localhost/login',
method: 'post',
jsonData: loginForm.getValues()
...
success: ...
even with Ext.JSON.encode(loginForm.getValues()) server is receiving as username=test&password=test which I need to be {"username":"test","password":"test"}
You should probably try something like
Ext.Ajax.request({
method: 'POST',
url: 'submit.php',
params : {
data: Ext.encode(loginForm.getValues())
},
success: function() {
},
failure: function() {
}
});
Source for reference
As is often the case with ExtJS, there's an easy answer. In the config of the loginForm:
Ext.create('Ext.form.Panel', {
title: 'Simple Form',
// The form will submit an AJAX request to this URL when submitted
url: 'save-form.php',
.... (blah blah blah)
jsonSubmit: true // <---- set this to TRUE
});
Set the property jsonSubmit: true. Then when you use loginForm.submit(), your object will be submitted as JSON rather than form params.
Here's a link to the form docs:
http://docs.sencha.com/extjs/4.2.3/#!/api/Ext.form.Panel
When a form is submitted, it is not submitted in JSON format.
In order to submit JSON string, Ext.Ajax.request must be used.
http://www.sencha.com/forum/showthread.php?132082-jsonData-in-submit-action-of-form
I just had to change
loginForm.submit({})
to
Ext.Ajax.request({})
and use
params: Ext.JSON.encode(loginForm.getValues()),
Bad DOCS.

Angular JS POST request not sending data

I am trying to send an JSON object to my webservice which is expecting JSON in the request data.
This my POST call from angularJS
$http({method: 'POST',
url: 'update.htm',
data: $.param($scope.cover),
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
}).success(function (data) {
// handle
});
Value for cover object
$scope.cover = {id:1, bean:{id:2}}
Iam getting 500 (InvalidPropertyException: Invalid property 'bean[id]' of bean class [BookBean]: Property referenced in indexed property path 'bean[id]' is neither an array nor a List nor a Map;)
In network, it is sending in this way
bean[id]:1
I think it should send like
bean.id:1
How to reslove this issue. Thanks in advance
Looks like the data is getting to the server and is causing an error there. There's a possible duplicate question that's been answered here - Post Nested Object to Spring MVC controller using JSON
Try posting your data like:
$http({method: 'POST',
url: 'update.htm',
data: $scope.cover,
}).success(function (data) {
// handle
});

couchDB: download results of list query as attachment

I have a list that produces a csv file. Querying that is simple, and if it is queryied from a link, it downloads the response as an attachment (provided the correct headers are sent).
However, I need to POST a potentially large amount of dynamically generated data (an array of keys). It's too large to just append to the url, i need to post the data as, well, data.
My usual ajax query is:
$.ajax({
type: 'POST',
dataType: 'text',
url: '/' + treatmentDatabaseString + '/_design/webview/_list/treatmentTable/treatmentTable?include_docs=true'
data: JSON.stringify({
'keys': keys // DATA THAT NEEDS TO BE POSTED
}),
error: function(status) {
alert('db error (keyed): ' + JSON.stringify(status));
},
success: function(data) {
// ..do stuff
}
});
Is there some way that I can alter the link so that it posts this data? or any other way I can make the result of this query download as an attachment?
If the incoming data is supposed to be JSON, you need to set contentType to application/json in your ajax call.

JSON, invalid label, issue consuming JSON

I have an issue with my JSON. We area getting it from a SOAP service I believe. I am using jQuery AJAX to try to consume the JSON. We are using the Asp.NET solution so I know about the "d" security feature and have in my dataFilter a way to try to get around that. I am getting the JSON back in Firebug but not to my local machine. The Service is on a domain separate from my local machine. I know about the cross domain policy issue but seems to be consuming the JSON in Firebug when I put the dataType as "jsonp" in the jQuery AJAX call.
If I set my dataType as "json" I get nothing back in Firebug.
The thing is my JSON has "\" slashes in it. I guess that is why Firebug is giving me an "invalid label" error. But I am not sure of that.
How can I filter out the "\" without doing the server side code again.
How can I just get the JSON back and alert on my page.
My jQuery Ajax call is below.
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
async: false,
url: "http://www.myexternaldomain.com/jservice/myservice.svc/CurrentJsonDataFullWeatherPanel",
data: "{}",
dataType: "jsonp",
dataFilter: function(data) {
// This boils the response string down
// into a proper JavaScript Object().
var msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
success: function(msg) {
// This will now output the same thing
// across any current version of .NET.
alert(msg);
},
error: function (result) {
alert('Failed: ' + result.status + ' ' + result.statusText);
}
});
});
My JSON output in Firebug shows like this.
{"d":"[{\"AirTemperature\":\"57.3\",\"BarometricPressure\":\"30.08\",\"CurrentRainRate\":\"\",\"DewPointTemperature\":\"30.7\",\"HeatIndex\":\"57.3\",\"HourlyRainAmount\":\"0.00\",\"LocalObservationTime\":\"10/14/2011 11:16:07 AM\",\"MonthlyRainAmount\":\"\",\"RelativeHumidity\":\"36\",\"SnowDepth\":\"0.0\",\"SolarRadiation\":\"\",\"SunRise\":\"7:09 AM\",\"SunSet\":\"6:22 PM\",\"TodayRainAmount\":\"0.00\",\"Visibility\":\"6561\",\"WindChill\":\"57.3\",\"WindDirection\":\"2\",\"WindGust\":\"11.4\",\"WindGustDirection\":\"92\",\"WindSpeed\":\"4.9\",\"YearlyRainAmount\":\"22.24\",\"StationTime\":\"10/14/2011 11:15:24 AM\"}]"}
Any suggestions?
Do I need to use a different way than jQuery to consume my JSON?
I should add that my fail alert is sending back 200 success but hitting the error.
Help is much appreciated. Thanks in advance.
Replace eval('(' + data + ')'); with $.parseJSON(data)
Docs: http://api.jquery.com/jQuery.parseJSON/