I am a newbie on Node.js. What I want to do here is to send some data in json format, from client side javascript to express.js server. Once I can do this, I will use those parameters that have been sent to the server to further retrieve information from MongoDB. The client side code is really simple, with a click event:
$.ajax({
url: 'http://localhost:8020/1',
type: 'post',
dataType: 'jsonp',
data: JSON.stringify({name: "test"}),
contentType: 'application/json',
success: function(data){
alert("success");
alert(data);
}
});
At the server side, the code looks like this:
var express = require('express');
var app = express();
var cons = require('consolidate'),
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server;
var mongoclient = new MongoClient (new Server('localhost', 27017,
{'native_parser' : true}));
var db=mongoclient.db('test');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.get('/1', function (req, res) {
db.collection('test').findOne({}, function (err, doc){
console.log(doc);
});
console.log(JSON.stringify(req.body));
var x = req.body.name;
console.log(x);
res.send({});
});
app.post('/1', function (req, res){
db.collection('test').findOne({}, function (err, doc){
console.log(doc);
});
console.log(req.body);
});
mongoclient.open(function (err, mongoclient) {
if (err) throw err;
app.listen(8020);
console.log("listening on port 8020");
});
When I make the client side ajax call, it seems that the server-side code successfully returns an item in my mongoDB database, but it fails to capture the data, which is {name : "test"} in this case.
Any one has any idea on this? Is this something related to cross domain issue? Thank you very much!
Aucun commentaire:
Enregistrer un commentaire