2015-10-05 15 views
0

你好,有人可以帮助我。我试图做一个简单的注册登录网站,我不能将响应传入我的回调我已经累了bind()和一个全局变量。问题是res.writeHead()Node.js将一个变量传递给回调

http.createServer(function (req,res){ 
var body = ''; 
if(req.method='POST'){ 
    req.on('data',function(chunk){ 
     body+=chunk; 
    }); 

    req.on('end',function(){ 
     console.log('POSTED: ' + body); 
     var content = body.split('&'); 
     if(content[0].split('=')[0] == 'login') 
     { 
      connectDB(dbURL,function(){ 
       User.findOne({ 
        'username':content[1].split('=')[1], 
        'password':content[2].split('=')[1]}, 
       function(err,loginUser){ 
        console.log(loginUser); 

        if (loginUser != null) 
        { 
         res.writeHead(301,{Location: './page.html'}); 
         res.end(); 
        } 

        db.close(); 
       }); 
      }); 
+0

您是否尝试过使用像express.js这样的框架?可能更容易使用... – CreasolDev

+0

你得到的错误信息是什么?我也建议使用快递。 – Louy

+0

是的,我知道它更容易,我一定会使用express.js,但首先我想从头学习的东西。并没有错误味精程序符文通常它只是不会重定向到page.html网站 – BlackIce

回答

0

我想这个问题是

if (loginUser != null) 

你试过吗?

if (loginUser !== null) 
+0

这不是我遇到的问题,我已经测试过,它可以找到用户。 – BlackIce

+0

所以你看到'console.log(loginUser)'输出?如果你进入'if',那么在代码的其他地方肯定会出现一些问题,我刚刚将'res.writeHead ...'粘贴到我正在处理的东西中,并且它可以工作。你有没有尝试过使用Mongoose查询API而不是回调? 'User.findOne({/ * blah * /})。exec()。then(/ * do stuff * /);' – piemonkey