我使用节点js(6)和mongodb(3.0)进行休息api设置。这是一个反应应用程序,我移植到Linux系统。没有对已经工作的源代码进行任何更改。我使用:mongod --config /etc/mongod.conf
这是我的配置文件:
dbpath=/home/mo/Documents/dev/data/mongodb/
#bindIp: [127.0.0.1, X.X.X.X]
bind_ip = 127.0.0.1
#logpath = /var/log/mongodb/mongod.log
logappend = true
这是我从mongodb通过api(dataservice.js)获取数据的代码:
var mongodb = require('mongodb');
var db = new mongodb.Db('expenses', new mongodb.Server('localhost', 27017, {}));
db.open(function (err, db_p) {
if (err) { throw err; }
db.collection('expenses', {strict:true}, function(err, collection) {
console.log("Connected successfully to server and expenses collection");
if (err) {
console.log("The 'expenses' collection doesn't exist.");
//populateDB();
}
});
});
exports.getCategories = function(req, res) {
console.log('get distinct categories function entered');
db.collection('expenses', function(err, collection) {
collection.distinct("category",function(err, items) {
console.log('search: distinct category');
console.log(items);
items.sort();
res.json(items);
// db.close();
});
});
}
这是我的server.js文件:
const express = require('express');
const dataHandler = require('./db/dataService.js');
const bodyParser = require('body-parser');
const app = express();
app.set('port', (process.env.PORT || 3001));
// Express only serves static assets in production
if (process.env.NODE_ENV === 'production') {
app.use(express.static('client/build'));
}
//allow cross origin access to avoid error received from using node-fetch, the problem does not exist when axios is used
app.use(function(req, res, next) {
//res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Origin', 'http://localhost:3000'); //allow access from this port
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
next();
});
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.get('/api/test', function(req, res) {
res.send([{name:'wine1'}, {name:'wine2'}]);
});
//test api: http://localhost:3001/api/categories
app.get('/api/categories', dataHandler.getCategories);
只是为了测试对http://localhost:3001/api/test
的调用工作正常。但是,http://localhost:3001/api/categories
不会返回数据。我知道数据存在。我有一些console.logs,数据服务正在被击中。我错过了什么?我已经在不同的系统上移动了这个代码并且它运行良好。
答案 0 :(得分:0)
问题解决了。经过几个小时的争吵才发现有一个简单的疏忽。我确实学到了一些看起来很棒的东西,所以这是值得的。我没有将正确的数据库名称传递给我的连接。我传递了集合名称。所以这一行应该说测试不费用:
var db = new mongodb.Db('expenses', new mongodb.Server('localhost', 27017, {}));
在这样的情况下,我只是将其删除或保留吗?