javascript - 类型错误 : something is not a function

标签 javascript node.js express

首先,我要说的是,我对 javascript 比较陌生,这段代码是为了尝试学习新东西,所以请随意评论任何内容,即使这不是我要问的具体问题。

我目前正在尝试将用于访问 MySQL 数据库的代码集中在 Express js 服务器中,并希望利用 Promise。这是我尝试过的:

let mysql = require('mysql');

    var connectionPool = mysql.createPool({
    host: 'localhost',
    user: 'user',
    password: 'password',
    database: 'database',
    connectionLimit: 10
});

function getConnection() {
    return new Promise(afterConnecting => {
        connectionPool.getConnection((err, connection) => {
            if (err) throw err;
            return afterConnecting(connection);
        });
    });
}

function queryConnection(connection, queryString) {
    return new Promise(consumeRows => {
        connection.query(queryString, function (err, rows) {
            connection.release();
            if (err) throw err;
            return consumeRows(rows);
        });
    });
}

exports.requests = {
    getAllEmployees: function () {
        const queryString = 'SELECT id, name FROM employees;
        return getConnection()
            .then(connection => {
                return queryConnection(connection, queryString);
            });
    }
};

我试图像这样调用getAllEmployees():

var express = require('express');
var router = express.Router();
var db = require('../database');

router.get('/', function (req, res) {
    db.getAllEmployees()
        .then(rows => {
            res.setHeader('Content-Type', 'application/json');
            res.send(JSON.stringify(rows));
        });
});

module.exports = router;

我的问题是我收到一个 TypeError,指出“db.getAllEmployees 不是函数”。调试 VS Code 时声称 db.getAllEmployees 确实是一个函数。可能是什么原因造成的?

最佳答案

您将其导出为 exports.requests.getAllEmployees 因此您必须将其用作:

 db.requests.getAllEmployees()

关于javascript - 类型错误 : something is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52929116/

相关文章:

node.js - "#!/bin/env"是什么意思(在 node.js 脚本的顶部)?

node.js - Mendix 设置问题 - 建议的代码不起作用

angularjs - 如何从包装在函数中的 sequelize 查询返回结果

javascript - 如何使用 promise 返回在 nodejs 的快速路由器中递归编辑的对象数组?

javascript - SugarCRM 中的 Javascript 密码验证文件在哪里?

javascript - 如何从图表js中的图表中删除轴线

javascript - 带有给出 "[object Object] does not fit the Control specification"错误的表格的 Google 图表

javascript - 将学生添加到虚拟教室

node.js - Slack 机器人安装以包含自定义表情符号?

javascript - express 是否提供来自隐藏(点)文件夹的静态文件