使用 Node.js 在 html 表中显示 mysql

我正在学习如何将 node.js 与 mysql 一起使用。我试图找到一些好的文档但徒劳无功。我现在可以在浏览器中显示我的 mysql 数据,但我想在某个时候通过我的 index.html 和一个 css 文件来处理它。


这是我的 app.js:


// moduels

var express = require('express');

var app = express();

var mysql = require('mysql');

var bodyParser = require('bodyParser')


// 

app.use(express.static(__dirname + '/public'));

app.use(bodyParser.urlencoded({extended: false}));


// connect to database

var con = mysql.createConnection({

    host: "localhost",

    user: "root",

    password: "1234",

    database: "BathBombs_DB"

});


// routes

app.get('/', function(request, response){

    console.log('GET request received at /') 

    con.query("SELECT * FROM customers", function (err, result) {

        if (err) throw err;

        else{

            response.send(result)

        }


    });

});


// listen for trafic and display on localhost:9000

app.listen(9000, function () {

    console.log('Connected to port 9000');

});

我的 index.html 网站如下所示:


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>Document</title>

</head>

<body>


    <form action="/" method="POST">

            <table type="text" name="firstname" ></table>

    </form>


</body>

</html>


米琪卡哇伊
浏览 384回答 3
3回答

开心每一天1111

您必须进行 ajax 调用才能从服务器获取结果并使用 javascript 与 HTML 内容绑定,如下所示:HTML 模板&nbsp;<table id="tableData" class="table table-fixed"><thead>&nbsp; <tr>&nbsp; </tr></thead><tbody class="tbody" ></tbody>这是进行ajax调用的脚本$(document).ready(() => {$.ajax({&nbsp; &nbsp; url: "http://localhost:9000/list",&nbsp;&nbsp; &nbsp; method: 'GET',&nbsp; &nbsp; success: function(response){&nbsp; &nbsp; &nbsp; &nbsp; if(response.rows.length > 0){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(let index = 0; index < response.rows.length; index++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var newRow = $("<tr>");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var cols = "";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var firstname = '';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var lastname = '';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var gender = '';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cols += '<td> '+ response.rows[index].firstname +'</td>';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cols += '<td> '+ response.rows[index].lastname +'</td>';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cols += '<td> '+ response.rows[index].gender+'</td>';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; newRow.append(cols);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $("#tableData .tbody").append(newRow);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }})})

哈士奇WWW

一种简单的方法是使用像 Knex JS 这样的查询构建器。它提供了更好的体验并且更易于使用。我相信以下代码对您有意义:const knex = require('knex');const http = require('http');const knex = require('knex')({&nbsp; client: 'mysql',&nbsp; connection: {&nbsp; &nbsp; host : '127.0.0.1',&nbsp; &nbsp; user : 'your_database_user',&nbsp; &nbsp; password : 'your_database_password',&nbsp; &nbsp; database : 'myapp_test'&nbsp; }});const record = await knex.select('title', 'author', 'year').from('books');const displayBody = record.map(single => {&nbsp; &nbsp;return `<tr>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<td>${single.title}</td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<td>${single.author}</td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<td>${single.year}</td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</tr>`;})let handleRequest = (request, response) => {&nbsp; &nbsp; response.writeHead(200, {&nbsp; &nbsp; &nbsp; &nbsp; 'Content-Type': 'text/html'&nbsp; &nbsp; });&nbsp; &nbsp; response.write('<!DOCTYPE html>&nbsp; &nbsp; <html>&nbsp; &nbsp; <head>&nbsp; &nbsp; &nbsp; <meta charset="UTF-8">&nbsp; &nbsp; &nbsp; <meta name="viewport" content="width=device-width, initial-scale=1.0">&nbsp; &nbsp; &nbsp; <meta http-equiv="X-UA-Compatible" content="ie=edge">&nbsp; &nbsp; &nbsp; <title>Homepage</title>&nbsp; &nbsp; </head>&nbsp; &nbsp; <body>&nbsp; &nbsp; &nbsp;<table>&nbsp; &nbsp; &nbsp; &nbsp; <thead>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <th>Title</th>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <th>Author</th>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <th>Year</th>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </tr>&nbsp; &nbsp; &nbsp; &nbsp; </thead>&nbsp; &nbsp; &nbsp; <tbody>');&nbsp; &nbsp; response.write(displayBody);&nbsp; &nbsp; response.write('</tbody>&nbsp; &nbsp; &nbsp; &nbsp; </table>&nbsp; &nbsp; &nbsp; </body>&nbsp; &nbsp; </html>');&nbsp; &nbsp; response.end();};http.createServer(handleRequest).listen(8000);在上面的代码中,我们从books表中获取数据以显示或返回。

12345678_0001

首先,您需要“发送/发送”您的“index.html”文件到浏览器。为此,您需要定义一个如下所示的 API 端点(它将 index.html 发送到浏览器)。/* GET home page. */app.get('/', getMainPage);function getMainPage(req, res) {&nbsp; console.debug('Route for mainViewpage: ' + __dirname );&nbsp; console.log(process.env);&nbsp; var mainViewFile = __dirname + '/../public/views/index.html'; // Replace&nbsp; this with path to your index.html file&nbsp; console.log('mainView log' , mainViewFile);&nbsp; fs.readFile(mainViewFile, function (err, html) {&nbsp; &nbsp; if (err) {&nbsp; &nbsp; &nbsp; throw err;&nbsp; &nbsp; }&nbsp; &nbsp; res.writeHeader(200, {"Content-Type": "text/html"});&nbsp; &nbsp; res.write(html);&nbsp; &nbsp; res.end();&nbsp; });}完成此操作后,请遵循@priya tarun 在上一个答案中给出的方法。注意:您还需要在 html 文件中包含 Jquery。您的“index.html”看起来像这样。我还没有完全测试,你可以做那部分。<!DOCTYPE html><html><head>&nbsp; &nbsp; <meta charset="UTF-8">&nbsp; &nbsp; <meta name="viewport" content="width=device-width, initial-scale=1.0">&nbsp; &nbsp; <meta http-equiv="X-UA-Compatible" content="ie=edge">&nbsp; &nbsp; <title>Document</title>&nbsp; &nbsp; <!--Inlcudes JQuery -->&nbsp; &nbsp; <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>&nbsp;</head><body>&nbsp; &nbsp; <form action="/" method="POST">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <table type="text" name="firstname" ></table>&nbsp; &nbsp; </form></body>$(document).ready(() => {$.ajax({&nbsp; &nbsp; url: "http://localhost:9000/getCustomerData",&nbsp;&nbsp; &nbsp; method: 'GET',&nbsp; &nbsp; success: function(response){&nbsp; &nbsp; &nbsp; &nbsp; if(response.rows.length > 0){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(let index = 0; index < response.rows.length; index++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var newRow = $("<tr>");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var cols = "";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var firstname = '';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var lastname = '';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var gender = '';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cols += '<td> '+ response.rows[index].firstname +'</td>';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cols += '<td> '+ response.rows[index].lastname +'</td>';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cols += '<td> '+ response.rows[index].gender+'</td>';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; newRow.append(cols);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $("#tableData .tbody").append(newRow);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }})})</html>注意:将您的 API 端点重命名为“/getCustomerData”而不是“/”来获取客户数据。使用 API 端点“/”将“index.html”提供给客户端/浏览器。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript