简体   繁体   English

在node.js中打印从数据库检索到的数据作为响应

[英]Printing the data retrieved from database as response in node.js

I'am beginner of node.js,Sorry if I went wrong. 我是node.js的初学者,很抱歉,如果我做错了。

Instead of printing data in console.log(),I want to print at localhost:3000. 我不想在console.log()中打印数据,而是要在localhost:3000上打印。

Here I retrieved data from MYsql database,Everything went right when I done with console.log(). 在这里,我从MYsql数据库中检索了数据,当我完成console.log()时,一切正常。 But it went wrong when I written my code with http request and response. 但是,当我用http请求和响应编写代码时,出现了错误。

My db.js is 我的db.js是

  var http = require("http");
  var port = 3000;
  var serverUrl = "localhost";
  var mysql = require('mysql');
  var connection = mysql.createConnection({

        host : 'localhost',
        user : username,
        password: password,
        database: "wst"

  });

   var server = http.createServer(function(req, res) {

   console.log("Request: " + req.url);
   connection.connect();

   connection.query('select * from welcome',function(err, results, fields){

    //console.log(results);
    //console.log(fields);
     var html = "<p>Registered users are " + results + ".</p>";
     res.end(html);

        });

    connection.end();

  });



  console.log("Listening at " + serverUrl + ":" + port);

  server.listen(port, serverUrl);

And the output in browser is: 浏览器中的输出为:

Registered users are [object Object],[object Object]. 注册用户为[对象对象],[对象对象]。

And error in command prompt is: 命令提示符中的错误是:

cannot enqueue handshake after invoking quit. 调用退出后无法排队握手。

If I'm completely wrong give me some tutorials on node.js. 如果我完全错了,请给我一些关于node.js的教程。

Based on the comments, it sounds like you're doing some processing on the client to bind it to a template after fetching it through ajax? 根据评论,听起来您在通过ajax提取客户端后正在客户端上进行一些处理,以将其绑定到模板?

Given that, you should consider not doing any templating on the server and instead just sending the json data, eg rather than <p>Registered users are " + util.inspect(results) + ".</p>"; you would just do util.inspect(results) . 鉴于此,您应该考虑不对服务器做任何模板处理,而只是发送json数据,例如,而不是<p>Registered users are " + util.inspect(results) + ".</p>";您只需做util.inspect(results)

You'll probably want to set the Content-Type header as well to application/json so that any magic your clientside framework wants to do by inspecting the headers will work. 您可能还希望将Content-Type标头设置为application/json以便客户端框架希望通过检查标头执行的任何操作都可以使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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