I am sending a credentials JSON object with the following request to node.js:
credentials = new Object();
credentials.username = username;
credentials.password = password;
$.ajax({
type: 'POST',
url: 'door.validate',
data: credentials,
dataType: 'json',
complete: function(validationResponse) {
...
}
});
On the server side i would like to load the submitted credentials into a JSON object to use it further on..
However, I don't know how to get the JSON out of the req object...
http.createServer(
function (req, res) {
// How do i acess the JSON
// credentials object here?
}
).listen(80);
(i have a dispatcher in my function(req, res) passing the req further on to controllers, so i would not like to use the .on('data', ...) function)
At server side you will do: var url = require( "url" ); var queryString = require( "querystring" ); http. createServer( function (req, res) { // parses the request url var theUrl = url. parse( req.
Example - Parsing JSONUse the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.
By default, you won't be able to parse JSON from the body of an incoming request with Express.
At the server side you will receive the jQuery data as request parameters, not JSON. If you send data in JSON format, you will receive JSON and will need to parse it. Something like:
$.ajax({
type: 'GET',
url: 'door.validate',
data: {
jsonData: "{ \"foo\": \"bar\", \"foo2\": 3 }"
// or jsonData: JSON.stringify(credentials) (newest browsers only)
},
dataType: 'json',
complete: function(validationResponse) {
...
}
});
At server side you will do:
var url = require( "url" );
var queryString = require( "querystring" );
http.createServer(
function (req, res) {
// parses the request url
var theUrl = url.parse( req.url );
// gets the query part of the URL and parses it creating an object
var queryObj = queryString.parse( theUrl.query );
// queryObj will contain the data of the query as an object
// and jsonData will be a property of it
// so, using JSON.parse will parse the jsonData to create an object
var obj = JSON.parse( queryObj.jsonData );
// as the object is created, the live below will print "bar"
console.log( obj.foo );
}
).listen(80);
Note that this will work with GET. To get the POST data, take a look here: How do you extract POST data in Node.js?
To serialize your object to JSON and set the value in jsonData, you can use JSON.stringify(credentials)
(in newest browsers) or JSON-js. Examples here: Serializing to JSON in jQuery
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With