【问题标题】:How to connect to mysql properly in nodejs?如何在nodejs中正确连接mysql?
【发布时间】:2016-12-12 04:59:04
【问题描述】:

我在这里尝试做的是查询 mysql 数据库,但是当我执行我的查询时,它只是永远加载,直到超时都没有错误,如何解决这个问题?下面是我的 db.js 代码:

Db.js:

var mysql = require("mysql");
var settings = require("../settings");

    exports.executeSql = function (sql, callback) {
        var conn = new mysql.createConnection(settings.dbConfig);
        conn.connect(function(err){
            if(err){
                console.log(err + "1");
                return;
            }

            console.log(conn.log + "2");
        })

}; 

这是我的 bassCtrl.js:

var db = require("../core/db");
var httpMsgs = require("../core/httpMsgs");

    exports.get_user = function(req, resp) {


        db.executeSql("select * from mst_user", function(data, err) {
            console.log("in controller");
            if (err) {
                httpMsgs.show500(req, resp, err);
            } else {
                httpMsgs.sendJson(req, resp, data);
            };
        });
};

这是我的 routes.js

var express = require('express');
var bassCtrl = require("../controllers/bassCtrl");
var httpMsgs = require("../core/httpMsgs");
var jwt = require('jsonwebtoken');

module.exports = function(app, express) {
    var router = express();

    router.route('/get_user').get(bassCtrl.get_user);


return router;
};

下面是我的 HttpMsgs.js :

var settings = require("../settings");

exports.show500 = function(req, resp, err) {
    if (settings.httpMsgsFormat === 'HTML') {
        resp.writeHead(500, "Internal Error occuared", {"Content-Type":"text/html"});
        resp.write("<html><head><title>500</title></head><body>500: Internal Error. Details: " + err + "</body></html>");
    } else {
        resp.writeHead(500, "Internal Error occuared", {"Content-Type":"application/json"});
        resp.write(JSON.stringify({ data: "Error occurred: " + err }));
    }
    resp.end();
}

exports.sendJson = function(req, resp, data) {
    resp.writeHead(200, {"Content-Type":"application/json"});
    if (data) {
        resp.write(JSON.stringify(data));
    }
    resp.end();
}

exports.show405 = function(req, resp) {
    if (settings.httpMsgsFormat === 'HTML') {
        resp.writeHead(405, "Method not supported", {"Content-Type":"text/html"});
        resp.write("<html><head><title>405</title></head><body>405: Method not supported.</body></html>");
    } else {
        resp.writeHead(405, "Method not supported", {"Content-Type":"application/json"});
        resp.write(JSON.stringify({ data: "Method not supported"}));
    }
    resp.end();
}

exports.show413 = function(req, resp) {
    if (settings.httpMsgsFormat === 'HTML') {
        resp.writeHead(404, "Resource not found", {"Content-Type":"text/html"});
        resp.write("<html><head><title>413</title></head><body>404: Resource not found.</body></html>");
    } else {
        resp.writeHead(404, "Resource not found", {"Content-Type":"application/json"});
        resp.write(JSON.stringify({ data: "Resource not found"}));
    }
    resp.end();
}

exports.show413 = function(req, resp) {
    if (settings.httpMsgsFormat === 'HTML') {
        resp.writeHead(413, "Request Entity Too Large", {"Content-Type":"text/html"});
        resp.write("<html><head><title>413</title></head><body>413: Request Entity Too Large.</body></html>");
    } else {
        resp.writeHead(413, "Request Entity Too Large", {"Content-Type":"application/json"});
        resp.write(JSON.stringify({ data: "Request Entity Too Large"}));
    }
    resp.end();
}

exports.send200 = function(req, resp) {
    resp.writeHead(200, {"Content-Type":"application/json"});
    resp.write(JSON.stringify(
        {status: "success", code: 200}
    ));
    resp.end();
}

exports.showHome = function(req, resp) {
    if (settings.httpMsgsFormat === 'HTML') {
        resp.writeHead(200, {"Content-Type":"text/html"});
        resp.write("<html><head><title>200</title></head><body>Your server connected dude ! :)</body></html>");
    } else {
        resp.writeHead(200, {"Content-Type":"application/json"});
        resp.write(JSON.stringify(
            {status: "Your server connected dude ! :)"}
        ));
    }
    resp.end();
}

这是我的 settings.js:

exports.dbConfig = {
    user: "root",
    password: "",
    host: "localhost",
    database: "zouk"
};

exports.httpMsgsFormat = "json";

当我触发 localhost:5000/get_user 时,它只是加载直到超时,我的 console.log 打印此行 console.log(connection.log + "2"); 并以 undefined 作为值。有什么我想念的吗?

等一下,为什么我的问题评分为负?

【问题讨论】:

    标签: javascript mysql node.js database-connection


    【解决方案1】:

    您没有在 Db.js 文件中执行查询,并且您的代码也没有调用回调,这就是它运行到超时的原因。

    var connection = mysql.createConnection({
      host     : ***,
      user     : ***,
      password : ***,
      database : ***,
    });
    
    connection.connect();
    
    connection.query(sql, function(err, rows, fields) {
      if (err) throw err;
    
      console.log('The solution is: ', rows[0].solution);
      //your callback go here.
      // callback(rows);//pass whatever you need in.
    });
    
    connection.end();
    

    另外,您的控制器不需要httpMsgs。我觉得应该有。

    【讨论】:

    • 是的,我已经执行了我的 db.js 文件,我只是取消了名为 bassCtrl.js 的控制器文件的日期。我在这一行执行它 db.executeSql("select * from mst_user", function(err, rows, fields)
    • 您可以尝试使用 httpMsgs 跳过并直接使用 resp。在流程的每个步骤中使用console.log 进行观察。
    猜你喜欢
    • 1970-01-01
    • 2021-05-21
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多