完整的ajax请求或更多路由

Full ajax requests or more routes

本文关键字:多路 路由 请求 ajax      更新时间:2023-09-26

我正计划对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...!');
        }
    });
}); 

玉石模板部分(索引.玉石):

#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请求它elt?示例

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

我希望有人能理解我的担忧,并以正确的方式向我指出。

PS。抱歉我英语不好。

不要这样做。查看restful服务如何安排路线。例如,您注销用户的路线如下所示:

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响应。

至于jade模板,我建议您看看handlebars模板以及如何从服务器提供模板。除了更明智,他们也更快。我个人在客户端和服务器端都使用它。

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

哦,你的英语很好。