Node.js Express res.json to html page?

Node.js Express res.json to html page?

本文关键字:html page to json js Express res Node      更新时间:2023-09-26

我有一个小应用程序,如果出现问题,它会向客户端发送各种错误消息,基本上是json消息。

是否有可能以某种方式将这些消息呈现到HTML页面?

例如,我有一个简单的登录表单,用户名和密码,我把它发回node.js

app.post('/login', function (req, res) {
    var username = req.body.username; // etc...
    if (username === "George" && password === "cat") {
        res.json({message : "success"});    
    } else {
        res.json({message : "fail"});
    }
});

自然地,它会发送一个只有json的页面。当然可以。我怎样才能捕捉到这些信息?我能抓住他们吗?这算是好的设计吗?我知道闪光消息,我用过几次。我也知道我应该使用jQuery的.ajax函数,但我无法使它工作。

我真的很感谢你的意见。

使用jQuery是个好主意。详细的指南可以在这里找到。

http://api.jquery.com/jquery.post/

我还建议使用标准的HTTP状态码,主要是200(成功)和401(未授权)。

http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

基本上你可以做以下事情:

节点

app.post('/login', function (req, res) {
    var username = req.body.username; // etc...
    if (username === "George" && password === "cat") {
        res.json({status: 200, message : "success"});    
    }
    else {
        res.json({status: 401, message : "fail"});
    }
});
jQuery

$.post( "/login", function(loginData) {
})
  .done(function(data) {
      if(data.status === 200) {
          //logged in
      } else {
          //logged out
      }
  })
  .fail(function() {
      //error (bad connection)
});

如果你继续发送json数据,但在客户端你渲染json数据使用javascript,所以它看起来像html?:)

您可以创建一个html片段,并将该html中的值替换为响应中的数据,在本例中是一个错误。

https://jsfiddle.net/umx1bn7b/

$('#some-button').on('click', function() {
  //lets go make a request with some ajax call
  // lets say ajax call fails and responds with something like this:
  var error = {
    message: 'Could not retrieve data.',
    code: 403
  };
  //We can build a string of html, add the error fields to the html, and add that html to our document like so.
  var errorHtml = "<div class='error'><h3>Sorry, an error has occured.</h3><p>Message: _message</p><p>Code: _code</p></div>"
  .replace('_message', error.message)
  .replace('_code', error.code)
  // Add to document
  $('#error').html(errorHtml)  
});