Reputation: 806
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.
Upvotes: 0
Views: 705
Reputation: 6321
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);
});
Upvotes: 0
Reputation: 1039498
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);
});
Upvotes: 3
Reputation: 8325
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 :)
});
Upvotes: 1