如何通过res.render()函数将多个db.query的多个结果发送到客户端?

时间:2019-04-01 21:20:02

标签: html node.js ejs

我正在建立一个网站。我的客户端代码在EJS中,我的服务器代码在Node.js中。我通过res.send();成功发送了db.query的结果变量。但是现在我想使用两个查询,并检索这些查询的值并将其发送到客户端。但是,如果我仅使用一个变量,那么它很好,但是当我在客户端中使用2个查询的两个变量时,它给我错误:错误:发送标头后无法设置标头。

这是我的login.js文件:

count

这是我的EJS,即login.ejs文件代码:

在这里,我使用result1 [0] .name作为标题。和result2 [i] .ph进入for循环。

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;
                };


            },

我尝试了几种通过res.render()发送变量result1和result2的方法,但是只有当我从客户端删除result2代码时,它才运行。

我遇到错误:

  <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>

帮助表示赞赏。让我知道是否还有其他需要。

1 个答案:

答案 0 :(得分:0)

Promise包的mysql版本:mysql2。使用诺言,您可以等待Promise解析或拒绝类似于sync代码的代码。

您可以实现您想要达到的目标:

const mysql = require('mysql2/promise');

module.exports = {


  inserttest : async (req,res) => {

    // let query = "SELECT * FROM `login` where username"; // query database to get all the players

    const connection = await mysql.createConnection({host:'localhost', user: 'root', database: 'test'});
    try {
      const [rows, fields] = await connection.execute('SELECT * FROM login WHERE username = ? AND password = ?', [username, password]);
    } catch (e) {
      console.error(e);
      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]
    ];

    try {
      // will wait till execution finishes
      await connection.execute(sqlq, [values]);
      console.log("1 row inserted successfully");
    } catch (e) {
      console.error(e)
    }
    var result2= doQuery1();

    res.render('mytest',
               {
      url:"/mytest",
      title:"WELCOME2",
      results1:result,
      results2:result2

    });
  }

  async function doQuery1(){
    let query = "SELECT * FROM usertest WHERE kitno IN(select kitno from login where username = ? AND password = ?)"; 
    var resource;
    try {
      const connection = await mysql.createConnection({host:'localhost', user: 'root', database: 'test'});
      resource = await connection.execute(query, [username, password]);
      return resource;
    } catch (e) {
      console.error(e);
    }
  };
}

以这种方式使用promiseasync/await可以使它像是连续的。