我希望能够在 SQL 查询的回调中使用 res.sendFile(__dirname + '/index.html');
。我不能这样做,因为它说:
sendFile isnt a function.
我有 SQL 查询 SELECT * FROM table,其回调和参数为 (req, res, result)
如何在回调中执行此操作?
这是一些代码:
app.post('/home', (req, res) => {
username = 'myuser';
con.query(`SELECT row FROM table`, (req, res, err, result) => {
var check = result.includes(username);
if ( check == true ) {
res.sendFile(__dirname + '/err.html');
} else if (check == false) {
res.sendfile(__dirname + '/index.html');
}
});
});
最佳答案
当给定函数有回调时,该回调的参数是固定的。对于con.query()
,参数是(err, result)
、一个错误和一个结果。
您实际上正在做的是将错误重命名为 req
,将结果重命名为 res
,并尝试调用 res.sendFile()
它实际上是在查询结果上调用 sendFile()
,这不是一个东西。
您不需要尝试传递 req 和 res:这些变量已经在更高的范围中定义,因此您可以访问它们。
因此您的代码片段应该是:
app.post('/home', (req, res) => {
username = 'myuser';
con.query(`SELECT row FROM table`, (err, result) => {
var check = result.includes(username);
if ( check == true ) {
res.sendFile(__dirname + '/err.html');
} else if (check == false) {
res.sendfile(__dirname + '/index.html');
}
});
});
关于mysql - sql 查询回调中的 res.sendFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54772040/