【发布时间】:2020-08-29 21:35:02
【问题描述】:
我看到Here 发布了一个类似的问题,但他们使用的是 MEAN-Stack。
我目前只是使用“setTimeout”函数等待几秒钟,然后使用 fetch api 从服务器请求新数据,以便有时间进行更新,但这感觉不是正确的方法。有没有一种简单的方式让前端只有在Express中更新数据库后才更新?我是 Node 新手,请见谅。
app.js:
const express = require('express');
const app = express();
const mysql = require('mysql');
let viewData = {
//html data
}
var pool = mysql.createPool({
connectionLimit : 10,
host: "localhost",
port: 3306,
database: 'testing',
user: "root",
password: "pass"
});
function sql(type) {
if(type == 'select') {
//Select query here
}
if(request == 'addRow') {
//Insert query here
}
}
app.get(`/`, function (req, res) {
res.sendFile('./views/index.html', {root: __dirname});
})
app.post('/api/add', function(req, res){
res.setHeader('Content-Type', 'application/json');
sql('addRow')
});
app.get('/api/viewData', function (req, res) {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(viewData));
})
index.js:
function loadData() {
fetch('/api/viewData')
.then(z => z.json())
.then(a => {
//update html
})
}
function postData(a) {
fetch('/api/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
//data to send to app.js
})
}).then(setTimeout(function(){loadData();}, 3000))
}
【问题讨论】:
-
如果您在后端使用 Promise,则不需要超时。这意味着,在将响应返回到前端之前,您将等待向 db 写入数据的承诺。然后,您可以保证您的数据已经存在于来自前端的后续调用中。这是一个关于他们如何将 MySQL 调用包装到 Promise 中的示例。 stackoverflow.com/questions/36547292/…
标签: javascript mysql node.js express