【问题标题】:How do you properly export/import a NodeJs class and it's respective functions如何正确导出/导入 NodeJs 类及其各自的功能
【发布时间】:2020-04-20 19:24:04
【问题描述】:

背景:我正在使用 mysql 和 nodejs。我希望经常使用嵌套查询,因此为了避免“回调地狱”,我制作了一个简单的类,其中包含由 Promises 支持的函数。

问题: 将我的类导入所需文件后,我尝试在 /login 路由内的 POST 请求中调用 query(sql, params){...} 函数,但出现以下错误:@987654323 @ 注意:我的所有代码都可以编译,因此我的导入不存在文件位置问题。当我运行程序时出现问题。

代码:

Database.js :这是我要导出到我的 api.js 文件中的内容。

var mysql = require('mysql');

const configuration = {
    host: 'localhost',
    user: 'root',
    password: '******',
    database: 'myDB'
}

class Database {
    constructor(configuration) {
        this.connection = mysql.createConnection(configuration) //
    }

    query(sql, params) {
        return new Promise(function(resolve, reject) {
            this.connection.query(sql, params, function(err, result) {
                if(err) return reject(err)
                resolve(result)
            })
        })
    }
}
module.exports = Database

api.js :这是我的应用程序后端逻辑的位置。

.
.
.
var Database = require('../classes/Database')

//This is the route responsible for invoking my database query
router.post('/login', function(req,res,next) {
    const query1 = "SELECT * FROM users WHERE username = ? AND pass = ?"
    Database.query(query1, [req.body.username, req.body.password])
    .then((result) => {
        if (result.length) {
            if (req.session.username) {
                res.send('You are logged in')
            } else {
                req.session.username = req.body.username
                res.send('You have successfully logged in')
            }
        } else {
            res.send('Incorrect Credentials')
        }
    }).catch((err) => console.log(err))
 })

【问题讨论】:

  • module.exports = new Database 在您的 Database.js 文件中进行简单的 1 字修复。您只需要实例化您的对象。您可以在模块中或外部进行,没有区别。
  • 我投票结束这个问题,因为基本语法问题,在技术上也是数百个类似问题的重复。

标签: javascript mysql node.js


【解决方案1】:

querymethodDatabase 可以在实际的 Database 对象上调用。你称呼它的方式 (Database.query),它必须是 static method 类的 Database

要使用query,您必须在某处初始化Database,例如带有const database = new Database(config);。然后您可以访问该对象并调用query:database.query(...)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    • 2018-02-23
    相关资源
    最近更新 更多