Node.js的一个问题,第一次访问可以返回页面,第二次无法返回

使用art-template渲染模板html,第一次可以正确的返回信息,第二次转个圈就报错了,折腾半天了,望解答

代码如下

==>router.js

const fs = require("fs");
const readPage = require("./read-page");
const url = require("url");
const queryID = require("./query");

function bind(server){
    server.on("request", (request, response)=>{
        
        const myURL = new URL(request.url, "https://127.0.0.1:8080/");
        
        if (request.url === "/") {
            response.end(readPage.html);
        } else if (myURL.pathname === "/query") {
            
            let str = myURL.search;
            let id = str[str.length - 1];
            let aa = queryID(id, html => {
                response.end(html);
            });
            
        } else {
            fs.readFile("." + request.url, "utf8", (err, data)=>response.end(data));
        }
    });
}

module.exports.bind = bind;
==>query.js

const template = require("art-template");
const mysql = require("mysql");

template.defaults.root = "./";

const connection = mysql.createConnection({
    host: "127.0.0.1",
    password: "208200",
    database: "onepiece",
    user: "root"
});

connection.connect();

module.exports = (id, fn)=>{
    id = id || 1;
    let sql = `select * from users where id = ${id}`;
    console.log(sql);
    connection.query(sql, (err, data)=>{
        if (err) throw err;
        let html = template("./index.html", { data });
        fn(html);
        
        connection.end();
    });
};

错误信息如下

C:\Users\QingChen\Desktop\Develop\Nodejs\6-optionSql\query.js:20
                if (err) throw err;
                         ^

Error: Cannot enqueue Query after invoking quit.
    at Protocol._validateEnqueue (C:\Users\QingChen\Desktop\Develop\Nodejs\6-optionSql\node_modules\mysql\lib\protocol\Protocol.js:215:16)
    at Protocol._enqueue (C:\Users\QingChen\Desktop\Develop\Nodejs\6-optionSql\node_modules\mysql\lib\protocol\Protocol.js:138:13)
    at Connection.query (C:\Users\QingChen\Desktop\Develop\Nodejs\6-optionSql\node_modules\mysql\lib\Connection.js:201:25)
    at module.exports (C:\Users\QingChen\Desktop\Develop\Nodejs\6-optionSql\query.js:19:13)
    at Server.<anonymous> (C:\Users\QingChen\Desktop\Develop\Nodejs\6-optionSql\router.js:17:13)
    at Server.emit (events.js:209:13)
    at parserOnIncoming (_http_server.js:733:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:115:17) {
  code: 'PROTOCOL_ENQUEUE_AFTER_QUIT',
  fatal: false
}
阅读 4.2k
2 个回答

query 的回调里直接调用了 connection.end(); ,然后这个 connection 就不能用了。再 query 自然出错。

在函数里创建连接啊

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题