0

我正在使用 nodejs、nowjs、codeigniter 和 mysql 编写应用程序。我使用数据库来存储会话。有没有一种好方法可以检查和检索 nodejs 中的会话 cookie?因此,例如,如果我需要使用 nowjs 检查用户是否拥有数据库中即将被删除的特定行。例如:

服务器:

//some code here to get session cookie and retrieve stored data from database

var session = { user_id: //userid from database }

everyone.now.deleteGuestbook = function(recordId) {
    var owner_id = client.query(
        'SELECT owner_id FROM guestbook WHERE id = ?',
        [recordId]
    );
    if (session.user_id === owner_id) {
        client.query(
        'DELETE FROM guestbook WHERE id = ?',
        [recordId], function() {
                 everyone.now.deleteRecord;
            }
        );
    }
}

客户:

//Delete guestbook record
$('#guestbook_records li').live('click', function(e) {
    if ($(e.target).is('a.delete')) {
        var id = $(this).find('a.delete').attr('href');
        dialogBox('warning', 'Are you sure you want to delete the record?',
            function() {
                now.deleteGuestbook(id);
            });
    }
    else {
        return;
    }
    return false;
});

now.deleteMessage = function(id) {
    $('li[class="' + id + '"]').slideUp(400, function() {
        $(this).remove();
    });
};
4

2 回答 2

3

会话 ID 通常保存在客户端 cookie 中,这些 cookie 在 httpServer 处理程序中显示为 request.headers.cookie。

您需要知道包含会话 ID 的 cookie 的名称,然后:

var cookies=(function(str){                     # create hash from cookie string
      var result={};
      str.split(/;\s+/).forEach(function(e){
        var parts=e.split(/=/,2);
        result[parts[0]]=parts[1]||'';
      });
      return result;
    })(request.headers.cookie),
    sessionCookieName='session',                # name of cookie holding session id
    sessionId=cookies[sessionCookieName]||'';   # session id or ''
于 2011-05-17T22:19:18.390 回答
1

你的客户端代码很乱

// live is bad and inefficient
$('#guestbook_records li').live('click', function(e) {
    // this kind of check seems horrid
    if ($(e.target).is('a.delete')) {
        // not very optimum to find it. 
        var id = $(this).find('a.delete').attr('href');
        dialogBox('warning', 'Are you sure you want to delete the record?',
            function() {
                now.deleteGuestbook(id);
            });
    }
    else {
        // why return here?
        return;
    }
    // return false should be in if block.
    return false;
});

试试这个

$("#guestbook_records li a.delete").click(function(e) {
    var id = this.href;
    dialogBox("warning", "Are you sure you want to delete the record?",
        function() {
             now.deleteGuesBook(id);
        });
    e.preventDefault();
}

.hasClass比较好

now.deleteMessage = function(id) {
    $('li').hasClass(id).slideUp(400, function() {
        $(this).remove();
    });
};
于 2011-05-17T22:05:00.640 回答