Node.js Express res.json到html页面?

我有一个小应用程序,如果出现问题,发送所有types的错误消息给客户端,基本上是json消息。

有可能以某种方式将这些消息呈现给HTML页面吗?

例如,我用简单的用户名和密码login表单,我把它发回到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在上面。 当然。 我怎样才能抓住这些信息? 我能抓住他们吗? 这是甚至好的devise? 我知道有关闪光消息,我已经使用了几次。 我也知道我应该使用jQuery的.ajax函数,但是我不能让它工作。

我真的很感激你的意见。

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

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

我也build议使用标准的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数据,但在客户端使用JavaScript呈现json数据,所以它看起来像html? 🙂

您可以创build一个html代码片段,并用您的响应中的数据replace该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) });