快递JS“这个”与app.get路由后未定义(..)(Express JS 'this

2019-07-23 03:12发布

我有被设计为用作API基本节点JS服务器,我创建了一个日志和数据库模块,我已经开始增加其他模块来处理不同的请求类型。

我使用Express.js和节点的MySQL

当我访问/v1/group我碰到下面的错误-

TypeError: Cannot read property 'database' of undefined
    at Group.getAll (C:\code\javascript\node\api\api\v1\groups.js:12:23)
    at callbacks (C:\code\javascript\node\api\node_modules\express\lib\router\index.js:161:37) ...

所以我recieving的请求,并要求后猜group.getAll()认为this是不明确的,但我不明白为什么,有没有一种方法来设置this或我有我的构建应用程序都错了?

sever.js

"use strict";

var Express = require('express');
var Log = require('./database/log');
var Database = require('./database/database');
var dbConfig = require('./dbconfig.json');

var Group = require('./api/v1/groups');


//Init express
var app = new Express();

//Init log and database
var log = new Log();
var database = new Database(dbConfig, log);

var initCallback = function() {
    //Init routes
    var group = new Group(database, log);

    //Group routes
    app.get('/v1/group', group.getAll);
    app.get('/v1/group/:id', group.getByID);

    app.listen(3000);
    log.logMessage("INFO", "Listening on port 3000");
};

//Test database connection
database.getConnection(function(err, connection) {
    if (err) {
        log.logMessage("FATAL", "Error connecting to database, check database is running and the dbconfig.json file is present and correct.");
        process.exit(1);
    }
    connection.end();

    initCallback();
});

database.js

"use strict";

var mysql = require('mysql');


var Database = function(dbConfig, log) {
    this.connected = false;
    this.log = log;

    this.log.logMessage("INFO", "Connecting to database with: Host - " + dbConfig.dbhost + ", Database port - " + dbConfig.dbport + ", Database name - " + dbConfig.dbname + ", User " + dbConfig.dbuser + ", Password length - " + dbConfig.dbpass.length);

    this.pool  = mysql.createPool({
        host : dbConfig.dbhost,
        user : dbConfig.dbuser,
        port: dbConfig.dbport,
        password : dbConfig.dbpass,
        database: dbConfig.dbname
    });
};

Database.prototype.getConnection = function() {
    var args = arguments;
    return this.pool.getConnection.apply(this.pool, arguments);
};

module.exports = Database;

groups.js

"use strict";

var Group = function(database, log) {
    this.database = database;
    this.log = log;
};

Group.prototype.getAll = function(req, res) {
    console.log(this); // --> undefined

    var query = 'SELECT * FROM invgroups WHERE published = 1';

    this.database.getConnection(function(err, connection) { // --> error line
        if (err) { res.send(500, "Database error"); }

        connection.query(query, function(err, results) {
            if (err) { res.send(500, "Database error"); }
            res.send(results);
        });

        connection.end();
    });

};


Group.prototype.getByID = function(req, res) {
    console.log(this);
    res.send({name: "Group Item 1"});
};

module.exports = Group;

Answer 1:

您需要正确绑定功能。

app.get('/v1/group', group.getAll);

只有经过getAll功能的处理程序,但功能本身没有的概念, thisthis是基于绑定,或在功能上是如何被调用基于上下文决定。 本博客文章是对理解函数上下文如何工作非常有用。

app.get('/v1/group', group.getAll.bind(group));


文章来源: Express JS 'this' undefined after routing with app.get(..)