ajax post to node.js express app?
-
11-10-2019 - |
Pergunta
I'm trying to authenticate before using ajax to insert into a database
$('#button').click(function () {
$.post('/db/', {
stuff: { "foo" : "bar"}
}, callback, "json");
});
Here's my node.js code:
server.get('/', function(req,res){
console.log(res);
res.render('index.ejs', {
locals : {
header: '#Header#'
,footer: '#Footer#'
,title : 'Page Title'
,description: 'Page Description'
,author: 'Your Name'
,analyticssiteid: 'XXXXXXX'
}
});
});
^^ this part works ok. It comes from a boilerplate, I can go to localhost and see the front page.
This next part is supposed to be where the mongo insert happens. This gives me a 404.
server.on('/db/', function(req,res){
console.log(req);
console.log(res);
var db = new mongo.Db( 'dbname' , new mongo.Server( 'localhost', 20003, {}), {});
db.open(function (err) {
db.collection('testCollection', function (err, collection) {
collection.insert(res.stuff);
});
});
});
What I'm trying to do is insert the object stuff
into testCollection.
Right now I'm getting a 404 on /db/
I'm sure this is very wrong. I don't think I'm supposed to use server.on, server.get doesn't work either. Please advise, thanks.
Solução
You have to use server.post
, since you're doing a POST request via jQuery.
server.on
will add a event listener to the server, in this case for the non-existent /db/
event, which never gets triggered by anything.
Please take your time and make sure to read the express.js Guide, the Node.js API Docs might come in handy too.
Outras dicas
Since you're expecting a post, your /db/ handler should be defined in a server.post
method. You're getting a 404 because the server doesn't have a route defined for the combination of POST and /db/.
you also should be authenticating the db connect and shouldn't be reconnecting to the db on each request
var db = new mongo.Db( 'dbname' , new mongo.Server( 'localhost', 20003, {}), {});
db.authenticate(user, password, function({ // callback }));
server.post('/db/', function(req,res){
db.open(function (err) {
db.collection('testCollection', function (err, collection) {
collection.insert(. . .);
});
});
});