我正在尝试在浏览器中以JSON格式显示数据!任何建议...。我在下面给出了我的JavaScript(.js)代码

  • 我正在尝试使用nodeJS执行此简单查询,但是它很重要
    似乎有效,数据库
  • 没有密码
  • 我要做的就是在JSON格式上显示答案
    从mysql数据库中获取的本地浏览器也位于
    本地系统
  • 我已经有一个名为的数据库,已经有一个名为的表,已经测试了
    在本地系统中创建,它只有两个名为 id
    内容

  • 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数据...有关如何解决它的任何建议!

    最佳答案

    这是您问题的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

    09-30 22:16
    查看更多