简体   繁体   中英

Node.js Express res.json to html page?

I've a small app, that sends all kind of error messages to client if something goes wrong, basically json messages.

Is it possible to somehow render those messages to a HTML page?

For example, I've simple login form with username and password, I send it back to 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"});
    }
});

Naturally, it sends a page with nothing but json on it. Of course. How can I catch these messages? Can I even catch them? Is this even good design? I know about flash messages, I've used them couple of times. I also do know that I should use jQuery's .ajax function for this, but I couldn't make it work.

I appreciate your input, truly.

Using jQuery is a good idea. A detailed guide can be found here.

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

I would also suggest using the standard HTTP status codes, mainly 200 (Success) and 401 (Not Authorised).

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

Essentially you can do the following.

Node

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)
});

How about you keep sending them json data, but at the client side you render the json data using javascript so it looks like html? :)

You can create a snippet of html and replace values in that html with data from your response, in this case, an error.

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)  
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM