简体   繁体   中英

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

I'am beginner of node.js,Sorry if I went wrong.

Instead of printing data in console.log(),I want to print at localhost:3000.

Here I retrieved data from MYsql database,Everything went right when I done with console.log(). But it went wrong when I written my code with http request and response.

My db.js is

  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.

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?

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) .

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.

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