NODEJS简单的SQL查询从本地数据库中获取并显示在本地系统上

我正试图在浏览器上以JSON格式显示数据! 任何build议….我已经给我下面的JavaScript(.js)代码


  1. 我试图执行这个简单的查询使用nodeJS,但似乎工作没有数据库的密码
  2. 所有我想要做的是显示在JSON格式的本地浏览器从MySQL数据库,也是在本地系统
  3. 我有一个名为test的表名为test的数据库已经在本地系统中创build,它只有两个名为idcontent的字段

var http = require('http'), mysql = require("mysql"); var connection = mysql.createConnection({ host: 'localhost', user: 'root', database: 'node' }); http.createServer(function (request, response) { request.on('end', function () { connection.query('SELECT id, content FROM test WHERE id IN (?, ?)',[1, 2], function(error, rows, fields) { response.writeHead(200); response.end(JSON.stringify(rows)); }); }); }).listen(8080); 

我的问题是:: nodejs服务器正在运行,但我无法在浏览器上显示JSON数据 …有关如何解决它的任何build议!


这是你的问题100%的工作代码!


 var http = require('http'); var mysql = require('mysql'); var connection = mysql.createConnection({ host: 'localhost', user: 'root', database: 'node' }); console.log('MySQL Connection details '+connection); http.createServer(function (request, response) { console.log('Creating the http server'); connection.query('SELECT id, content FROM test WHERE id IN (?,?)',[1, 2], function(err, rows, fields) { console.log('Connection result error '+err); console.log('no of records is '+rows.length); response.writeHead(200, { 'Content-Type': 'application/json'}); response.end(JSON.stringify(rows)); response.end(); }); }).listen(8084); 

我甚至添加了下面的快照


command prompt where the execution is done below


此搜索


JSON output seen in the browser below


图像2

在您的代码中添加一个内容types:

 response.setHeader("Content-Type", "application/json");