Node.js: MySQL 每次用户刷新时获取新数据做一些奇怪的事情

Node.js: MySQL Get New Data Every Time The User Refreshes Does Something Weird

我是 Node.js 的新手,所以这个问题可能很愚蠢但是:

我想出了如何获取 MySql 数据,然后从...中创建 HTML table 我还能够创建一行,您可以在其中删除MySql 中的行。我设法做到了,所以当您重新加载页面时,它会获取新数据。但是由于某种原因,它显示了部分信息,然后正确显示了...

代码:

var mysql = require("mysql");
var date = require("dateformat");
var express = require('express');
var app = express();
var result = [];
var happy;
var pug = require('pug');
var port = 3000
app.use(express.urlencoded());
app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
})
var conn = mysql.createConnection({
    host: "localhost",
    user: "admin",
    password: "myphpadmin",
    database: "tests"
});



var getdata = function (callback) {

    conn.query('SELECT Id, Description, Date, Amount, Merchant, Type, Sub, Source  FROM main', function (err, res, fields) {
        if (err) return err;
        if (res.length) {
            happy = append(res)
            callback(happy)
        }
        
    })

}



function append(result) {

        for (i in result) {
            data = { "Id": '<form action="delete" method="post"><input type="hidden" name="id" value="' + result[i].Id +'"><input type="submit" value="Delete"></form>', "Des": result[i].Description, "Date": date(result[i].Date, "mmmm d, yyyy"), "A": result[i].Amount, "M": result[i].Merchant, "T": result[i].Type, "Sub": result[i].Sub, "S": result[i].Source }
            result.push(data)
        }
        return result
}
app.set('view engine', 'pug')


app.post('/delete', function (request, response) {
    conn.query('Delete From main Where Id = ' + request.body.id, function (err, result) {
        if (err) { throw err }
        if (result.affectedRows == 0) { response.send('Bad Id') }
        else {response.send('Good Id!')}
    })
})

app.get('/', function (request, response) { 
    getdata(function (happy){ response.render('index', {
        result: happy
    }) });
    
});

示例table:

谢谢!

删除行并返回 table 后,现在也不会重新加载。我必须手动重新加载才能看到新的 table...有办法吗?

P.S。如果还有类似的问题请告诉我!

在追加函数中,您正在执行 result.push(data) 将数据追加到 mysql 的结果集,这就是为什么您有重复行和不同格式的原因。

如下所示在该函数中创建一个新数组,并return它而不是结果。

function append(result) {
        const table = []
        for (i in result) {
            data = { "Id": '<form action="delete" method="post"><input type="hidden" name="id" value="' + result[i].Id +'"><input type="submit" value="Delete"></form>', "Des": result[i].Description, "Date": date(result[i].Date, "mmmm d, yyyy"), "A": result[i].Amount, "M": result[i].Merchant, "T": result[i].Type, "Sub": result[i].Sub, "S": result[i].Source }
            table.push(data)
        }
        return table
}