NODEJS on simple SQL query fetching from the local database and displaying on local system

前端 未结 2 1674
有刺的猬
有刺的猬 2021-02-06 09:22

I am trying to display data in JSON format on the browser! any suggestions .... i have given my javascript (.js) code below


  1. I am trying to
相关标签:
2条回答
  • 2021-02-06 09:39

    This is a 100% working code for your question ! !


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

    I have even added the snapshot's below


    command prompt where the execution is done below


    image1


    JSON output seen in the browser below


    image2

    0 讨论(0)
  • 2021-02-06 09:54

    Add a content-type in your code:

    response.setHeader("Content-Type", "application/json");
    
    0 讨论(0)
提交回复
热议问题