我正在建立一个网站。我的客户端代码在EJS中,我的服务器代码在Node.js中。我通过res.send();成功发送了db.query的结果变量。但是现在我想使用两个查询,并检索这些查询的值并将其发送到客户端。但是,如果我只使用一个变量,那很好,但是当我在客户端中使用2个查询的两个变量时,这会给我错误:错误:发送标头后无法设置标头。
这是我的login.js文件:
var username;
var password;
var result;
module.exports = {
inserttest : (req,res) => {
// let query = "SELECT * FROM `login` where username"; // query database to get all the players
db.query('SELECT * FROM login WHERE username = ? AND password = ?', [username, password], function(error, result, fields) {
if (error) {
res.redirect('/login');
}
var moisture = 11232;
var ph = 1121;
var ec = 543;
var date1=new Date();
const sqlq='insert into usertest values ?';
var values = [
[result[0].kitno,moisture,ph,ec,date1]
];
db.query(sqlq, [values], function(error, results, fields) {
if(error)
{
console.log("error");
//var a
//res.send(500,'showAlert')
}
else{
console.log("1 row inserted successfully");
}
var result2= doQuery1();
res.render('mytest',
{
url:"/mytest",
title:"WELCOME2",
results1:result,
results2:result2
});
});
});
function doQuery1(){
let query = "SELECT * FROM usertest WHERE kitno IN(select kitno from login where username = ? AND password = ?)";
var resource;
db.query(query, [username, password], function(error, result4, fields){
resource=result4;
});
return resource;
};
},
这是我的EJS,即login.ejs文件代码:
这里我使用result1 [0] .name作为标题。并在for循环中添加result2 [i] .ph。
<main class="page-content">
<div class="container-fluid">
<h2>My Tests</h2>
<hr>
<div id="main">
<div id="left" class="container">
<br>
<form method="get" action="/insertvalues">
<input type="submit" value="Start Test" />
</form>
<% for (var i = 0; i < results2.length; i++) { %>
<%=results2[i].ph%>
<%}%>
<br>
我尝试了几种通过res.render()发送变量result1和result2的方法,但是只有当我从客户端删除result2代码时,它才运行。
我得到的错误:
_http_outgoing.js:491
throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:491:11)
at ServerResponse.setHeader (_http_outgoing.js:498:3)
at Array.write (C:\Users\Rohit\Desktop\Project_me\soil2\node_modules\finalhandler\index.js:285:9)
at listener (C:\Users\Rohit\Desktop\Project_me\soil2\node_modules\on-finished\index.js:169:15)
at onFinish (C:\Users\Rohit\Desktop\Project_me\soil2\node_modules\on-finished\index.js:100:5)
at callback (C:\Users\Rohit\Desktop\Project_me\soil2\node_modules\ee-first\index.js:55:10)
at IncomingMessage.onevent (C:\Users\Rohit\Desktop\Project_me\soil2\node_modules\ee-first\index.js:93:5)
at emitNone (events.js:106:13)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
我正在建立一个网站。我的客户端代码在EJS中,我的服务器代码在Node.js中。我通过res.send();成功发送了db.query的结果变量。但是现在我想使用两个查询...
Promise
程序包有mysql
版本:mysql2
。使用诺言,您可以等待Promise
解析或拒绝类似于sync
代码的代码。