完整的ajax请求或更多路由

时间:2014-09-15 10:20:29

标签: javascript ajax html5 node.js pug

我打算编写我的node.js网页。

我将node.js与express和jade模板一起使用。

我想使用对服务器的POST AJAX请求使其完全异步。 我的意思是只有一条路线如下:

router.get('/', function(req, res) {
    res.render('index', { "some": 'parameters'});
}

我通过客户端ajax调用请求,如:

$("#logout").click(function(event){
    event.preventDefault();
    var payload = {
        command: 'logout'
    };
    $.ajax({
        url: "/main_page_ajax",
        type: "POST",
        datatype: "json",
        contentType: "application/json; charset=utf-8",
        processData: false,
        data: JSON.stringify(payload),
        success: function (result) {
            var json = jQuery.parseJSON(result);
            if(json.done==1){
                $('#login_screen_clear').fadeIn("slow");
                $('#login_screen_logged').hide();
                show_message('Logout successful!');
            }
            else show_message('Something went wrong...!');
        }
    });
}); 

jade模板的一部分(index.jade):

#login_screen_logged
    .log_div
        h3 Hello 
            b#logged_name
            | !
        br
        br
        a#logout(href='/logout') Logout
#login_screen_clear
    //login form
    input#player_login(type='text', size='15', autocomplete='off')
    input#player_pass(type='password', size='15', autocomplete='off')
    input#login_button(type='submit', value='Login')

回到服务器端。处理ajax请求:

router.post('/main_page_ajax', function(req, res) {
   switch(String(req.body.command)){
       case 'logout':
           var resultJson = { };
           req.session.destroy(function(err) {
               resultJson.done=1;
               res.end(JSON.stringify(resultJson));
           });
       break;
   }
});

好的,这是我的问题:

  1. 这是node.js应用程序的好方法吗?

  2. 这种方式将使我将几乎所有容器存储在index.jade模板(隐藏的div)中,这将等待特定的调用。因此,随着应用开发的增多,这个文件会增长很多。 是否有更好的地方保留html / jade代码?也许Ajax要求itselt?实施例

    success: function (result) {
        var json = jQuery.parseJSON(result);
            if(json.done==1){
                $('#login_screen_clear').html("<a><bunch><of><html><code>")
                $('#login_screen_clear').fadeIn("slow");
                $('#login_screen_logged').hide();
                show_message('Logout Successful!');
            }
            else show_message('Something went wrong...!');
    }
    
  3. 我希望有人能理解我的担忧,并以正确的方式指出我。

    PS。抱歉我的英语很差。

1 个答案:

答案 0 :(得分:0)

不要这样做。了解宁静的服务如何安排他们的路线。 例如,您注销用户的路径如下所示:

router.post('/profile/:name/logout', function(req, res) {
    req.session.name = null; //Flush session if you are using express
    var token = req.session.token || '';
    token.invalidate(token); //Function to remove token from redis or whatever you are using
    res.status(200);
});

因此,此路由将刷新与该帐户关联的任何会话和/或令牌,并发回200响应。

至于玉石模板,我建议你看一下模板的把手和serve templates from the server的方法。除了更明智之外,它们也更快。我个人在客户端和服务器端都使用它。

获取请求;人们通常在没有任何身份验证的情况下提供html,当浏览器收到有效负载时,客户端javascript通过ajax和/或jwt对用户进行身份验证。

哦,你的英语非常适合。