简体   繁体   English

ajax发布到node.js表达app?

[英]ajax post to node.js express app?

I'm trying to authenticate before using ajax to insert into a database 我在尝试使用ajax插入数据库之前进行身份验证

$('#button').click(function () {       
  $.post('/db/', { 
   stuff: { "foo" : "bar"}
  }, callback, "json");
});

Here's my node.js code: 这是我的node.js代码:

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. 它来自样板,我可以去localhost看看头版。

This next part is supposed to be where the mongo insert happens. 下一部分应该是mongo插入发生的地方。 This gives me a 404. 这给了我一个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. 我要做的是将对象stuff插入testCollection。

Right now I'm getting a 404 on /db/ 现在我得到404 / 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. 我不认为我应该使用server.on,server.get也不起作用。 Please advise, thanks. 请指教,谢谢。

You have to use server.post , since you're doing a POST request via jQuery. 您必须使用server.post ,因为您正在通过jQuery执行POST请求。

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. server.on将向服务器添加一个事件监听器,在这种情况下是不存在的/db/ event,它永远不会被任何东西触发。

Please take your time and make sure to read the express.js Guide , the Node.js API Docs might come in handy too. 请花点时间并确保阅读express.js 指南 ,Node.js API文档也可能派上用场。

Since you're expecting a post, your /db/ handler should be defined in a server.post method. 由于您期望发布帖子,因此应在server.post方法中定义/ db / handler。 You're getting a 404 because the server doesn't have a route defined for the combination of POST and /db/. 你得到的是404,因为服务器没有为POST和/ db /的组合定义的路由。

you also should be authenticating the db connect and shouldn't be reconnecting to the db on each request 您还应该对db connect进行身份验证,并且不应在每次请求时重新连接到db

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(. . .);
    });
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM