JohnnSzm JohnnSzm - 2 months ago 7
Javascript Question

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.

Answer

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