简体   繁体   中英

How to display data from MySQL into HTML-Page with NodeJS

I'm new in Node JS and I'm trying to display the fetched data from my MySQL Table into a table in my HTML-File. But I couldn't find anything that helped me. I would really appreciate it if somebody can help me to get a solution: :) Here's my js-code:

 //app.js // Get the mysql service var mysql = require('mysql'); var express = require('express'); var app = express(); app.get('/', function (request, response) { fetchData(response); console.log('Done. Displayed Data.'); }); // Add the credentials to access your database var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'Breunninger', port: '3306' }); // connect to mysql connection.connect(function(err) { if(err){throw err;} console.log('Connected'); }); function executeQuery(sql, cb){ connection.query(sql, function( result, fields){ cb(result); }) } function fetchData(response){ executeQuery("SELECT username, tor, datum, sendungsstruktur FROM Buchung JOIN user ON(user.id = Buchung.userid)", function (result) { console.log(result); response.write('<div class="container-wrap"><table id="example" class="display"><tr>'); for(var column in result[0]){ response.write('<td> <label>' + column + '</label></td>'); response.write('</tr>'); } for(var row in result){ response.write('<tr>'); for(var column in result[row]){ response.write('<td>' + result[row][column]+ '</td>'); } response.write('</tr>'); } response.end('</table></div>'); }); }
 <div class="container-wrap"> <div class="flexslider"> <script src="app.js"></script> </div> </div>

There's a small (but critical,) error in the executeQuery function, the first argument should be the error object. so if you can re-write this as below your query should work.

function executeQuery(sql, cb){
    connection.query(sql, function( error, result, fields){
        if (error) {
            console.error("An error has occurred:", error);
        } else {
            cb(result);
        }   
    })
}

Node callback usually reserve the first argument for an error object, it's easy to miss this!

Also, we should be clear, the Node.js Express code will be running on the server side, so to see the results you need to point your browser to the host and port this is serving, eg http://localhost:3000/ (if you do:)

app.listen(3000);

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