1

nodejsその中で簡単なチャットアプリを作り始めました。このために、にいるすべてのユーザーにアクセスしたいと思いますmysql database

私のコードは次のようなものです:

JS

exports.authenticate = function(req, res) {

    //connection.connect();
    var sql="SELECT * from users where username='"+req.body.user+"' and password='"+req.body.pass+"' LIMIT 1";
    connection.query(sql, function(err, rows, fields) {
        if (err) throw err;

        //res.send('Your data is: ', rows);
        var str="Hi, <b>"+rows[0].name+"</b> ("+rows[0].email+")";

        sql="SELECT DISTINCT username,name from users ORDER BY name";
        connection.query(sql, function(err, datarows, fields) {
            if (err) throw err;
            //res.send('Your data is: ', rows+' <br/> All Users are : ', datarows.length+"<a href='/'>Login</a>");
            str+='<ul style="list-style:none;width:300px">';
            for(var index=0;index<datarows.length;index++)
            {
                str+="<li><a href='javascript:;'>"+datarows[index].name+", "+datarows[index].email+"</a></li>";
            }
            str+='</ul>';console.log(str);  
            console.log(str)//gives ul  
        });

        str+="<a href='/'>Login</a>";
        res.send(str);//this not gives the ul of other users
    });

}

上記のコードには、私が書いconsole.log(str)//gives ulたように文字列全体が出力されるという問題がありますHi, <b>Rohan</b> ("rohan@xyz.com")<ul><li><a>Something</a></li>....</ul>。しかし、res.send(str);送信のみHi, <b>Rohan</b> ("rohan@xyz.com")<a href='/'>Login</a>

  1. なぜこれが起こっているのですか?
  2. 私はそうでstr variableはありませんglobalか?
  3. 何度も使用できますres.send()か? はいの場合、どのように使用できますか?

上記のコードを使用できますか?jade次に、このためにどのコードを作成する必要がありますか?

私はこの回答を見つけましたデータフォームmongodb(Mongousモジュールを使用)をnodejsビュー(一時エンジンジェイドを使用)に渡す方法は?私の問題に関連する

app.get('/', function(req, res) {
  mgs(dbColl).find(function(data){
    res.render('yourview.jade', { data: data });
  });
});

次に、データにアクセスする方法yourview.jade

nodejs を使用する必要があるアプリケーションの種類についても知りたいですか?

少し早いですがお礼を。

4

1 に答える 1

0
  1. This is happening because Node is asynchronous. Your res.send(str) is executed immediately after calling your inner connection.query(), therefore the callback which adds more hasn't executed before the send.
  2. No, your str variable is not global.
  3. I do not believe so. If you want to write to the response before sending it, you can use res.write().

Yes you can use Jade instead of what you're doing now. Take a look at the Jade docs. They are full of examples of variables being used in jade. To summarize it for you though, you should be able to access a variable with #{variable}.

As for your last question, I'm really not sure what you're asking. You can use node for alot of stuff, from controlling quadcopters to web sites and services.

于 2013-03-08T06:29:08.690 に答える