2017-04-22 25 views
2

。首先,我是节点中的新手。我读过几乎所有类似的帖子,但无法弄清楚我的情况最好。我从发送房间名称的静态HTML文件发出ajax发布请求以加入。在服务器端,如果有这个特定名称的房间,我搜索我的mongodb。如果没有,我想回到上一页发送一条消息,如“没有这个名字的房间”。如果我尝试res.send或res.json,它会将我重定向到显示上述消息的空白页面。我不喜欢也做一个网址查询。有没有办法做到这一点?由于节点js如何将数据传递给静态html作为对ajax响应的调用

$('#btn2').click(function(){ 
      $.ajax({ 
       type: "POST", 
       url: '/joinRoom', 
       data: $('#roomJoin').val(), 
       dataType: 'json', 
       success: function (response) { 
        console.log(response); 
       } 

      }); 
     }) 

app.js

app.post('/joinRoom', checkAuthentication,function(req,res){ 
    console.log(req.body); 
    User.findOne({ createRoom:req.body.roomJoin }, function(err,obj){ 
     if(err){ 
      console.log(err.code); 
     } 
     else if(!obj) {   
      res.redirect('index_connected.html'); 

     } else if(obj){ 
      res.redirect('board.html'); 
     } 
    }); 

}) 

回答

0

url查询发送消息将是实现这一目标的最简单的方法。如果你不想要他们,你可以尝试下面的选择。

从您的服务器发送一个cookie并加载页面,检查您是否有Cookie。如果你有它,显示一条消息并删除co​​okie。如果不跳过它。

+0

感谢您的答复。通过查询发送信息没有安全问题; – nick314

0

你可以像这样

app.post('/joinRoom', checkAuthentication,function(req,res){ 
    console.log(req.body); 
    User.findOne({ createRoom:req.body.roomJoin }, function(err,obj){ 
     if(err){ 
      console.log(err.code); 
     } 
     else if(!obj) {   
      res.redirect("index_connected.html/?message=there isn't a room with this name"); 

     } else if(obj){ 
      res.redirect('board.html'); 
     } 
    }); 

}) 
+0

谢谢,但正如我写的,我不喜欢疑问 – nick314

相关问题