我试图基本了解db的CRUD操作如何与节点js一起使用。 我创建了两个单独的文件 - server.js和app.js. server.js包含用于访问数据库的代码,app.js通过'require'获得了对server.js的引用。 下面是我的server.js代码:
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8999;
var router = express.Router();
app.use(cors());
app.use('/cloudApi', router);
app.listen(port);
console.log('REST API is runnning at ' + port);
var dbp = "users";
var Users;
function initCloudant() {
var cloudantURL = appEnv.services.cloudantNoSQLDB[0].credentials.url || appEnv.getServiceCreds("users-cloudant").url;
var Cloudant = require('cloudant')({
url: cloudantURL,
plugin: 'retry',
retryAttempts: 10,
retryTimeout: 500
});
Users = Cloudant.use(dbp);
}
router.route('/tests').get(function (req, res) {
console.log("Inside tests api");
Users.find({
selector: {
"testName":"abc"
},
}, function(err, result) {
res.send(result);
});
});
当我使用命令:node server.js运行时,一切正常。 我也可以通过邮递员访问api。
在我的app.js中,我已经提到了这个:
var server= require('./dir/server.js');
当我运行命令节点app.js时 并尝试点击api,我收到错误:
TypeError: Cannot read property 'find' of undefined
at C:\Users\nodeApp\dir\server.js:80:13
at Layer.handle [as handle_request] (C:\Users\nodeApp\node_modules\express\lib\router\layer.js:
95:5)
at next (C:\Users\nodeApp\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\nodeApp\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\nodeApp\node_modules\express\lib\router\layer.js:
95:5)
at C:\Users\nodeApp\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\nodeApp\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\nodeApp\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\Users\nodeApp\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\anodeApp\node_modules\express\lib\router\index.js:47:12)
我不知道我错过了什么,以便api可以工作。
答案 0 :(得分:1)
您的initCloudant方法似乎永远不会被执行。
从get方法的成功回调中调用initCloudant,如下所示:
router.route('/tests').get(function (req, res) {
initCloudant() //call it here
console.log("Inside tests api");
Users.find({
selector: {
"testName":"abc"
},
}, function(err, result) {
res.send(result);
});
或者将User对象初始化为默认属性。