0

Im making a simple app to learn how node.js works. Using jquery and ajax i pass a JSON object to a node.js method. The problem is that i don't know how to get the specific JSON data in the node.js method.

client-side code:

 $(document).ready(function(){
 $('#guardarVehiculo').click(function(){
 var car = JSON.stringify(agregarCarro());
 $.ajax({
 type: 'POST',
 data: car,
 url: '/saveCar',
 dataType: 'JSON'
 }).done(function( response ) {
 console.log(response);
 });
 });
 });
 function addCar(){
 var id = getById('id').value;
 var brand = getById('brand').value;
 var model = getById('model').value;
 var transmission = getById('automatic').checked ? getById('automatico').value : getById('mechanic').value;
 var comment = getById('comment').value;
 var car = new Car(id, brand, model, transmission, comment);
 return car;
 }

node.js code:

var express = require('express');
var fs = require('fs');
var app = express();
app.get('/', function(req, res){
 res.sendFile(__dirname + "/index.html");
});
app.post('/saveCar', function(req, res){
 console.log(req);
});
var server = app.listen(8000, function(){
 var host = server.address().address;
 var port = server.address().port;
 console.log('Server running at: ' + host + ':' + port);
});

Thanks in advance.

asked Mar 5, 2016 at 6:10
2
  • 1
    If you're going to POST the data, you'll probably want a BodyParser that does this for you, otherwise GET data is easily available in req.query Commented Mar 5, 2016 at 6:21
  • Thanks for the advice, now i know what to use un every case. Commented Mar 5, 2016 at 6:30

3 Answers 3

3

You could use the bodyParser middleware

var app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.json());

and then req.body will contain the parsed JSON object:

app.post('/saveCar', function(req, res) {
 console.log(req.body);
});

There's just one gotcha. You need to set the proper Content-Type header when making the AJAX call so that the body parser knows that it should process JSON:

.ajax({
 type: 'POST',
 data: car,
 url: '/saveCar',
 contentType: 'application/json',
 dataType: 'JSON'
}).done(function( response ) {
 console.log(response);
});
DCruz22
8061 gold badge9 silver badges18 bronze badges
answered Mar 5, 2016 at 6:21
Sign up to request clarification or add additional context in comments.

1 Comment

I was exactly looking for that. Thanks a lot!
1

Answer to understand flow.

JSON data posted from client is received in req.body.

req.body contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser.

using body-parsing middleware to populate req.body as:

var app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.json());

magic req.body will server JSON data, sent by client:

app.post('/save-car', function(req, res) {
 //hey! i am req.body and i have all data :)
});
answered Mar 5, 2016 at 6:48

1 Comment

Thanks for the explanation!
0

Use BodyParser module.

Server:

var bodyParser = require("body-parser");
app.use(bodyParser.json());

Route:

cars{
 brand: "Tesla",
 model: "S-sport",
 color: "white"
}
app.post('/saveCar', function (req, res) {
 console.log(req.body);
 //to response back as Json.
 res.json(cars);
});
answered Mar 5, 2016 at 6:58

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.