尝试使用nodejs构建restapi我收到此错误
TypeError: Cannot call method 'getCategories' of undefined
我的项目结构是这样的
模型
- dbhandler.js
node_modules
的package.json
app.js
dbconnection.js
我的dbhandler代码在这里
var db = require('../dbconnection');
var getData = {
getCategories : function() {
var sql = "SELECT * FROM categories"
db.connection.connect();
db.connection.query(sql,function(error, results, fields){
if (!error){
console.log('The solution is: ', results);
console.log('The solution fields is: ', fields);
} else{
console.log('Error while performing Query.');
}
});
}};
module.exports = getData;
我的app.js代码在这里:
var dbhandler = require('./models/dbhandler')
var router = express.Router();
router.get('/', function(req, res) {
dbhandler.getData.getCategories();
res.json({ message: 'hooray! welcome to our api!' });
});
答案 0 :(得分:1)
当您通过此var dbhandler = require('./models/dbhandler')