帮我stackoverflow!尽管连接到数据库并且(显然)正确定义了配置的所有部分(它们超时),我似乎无法在邮递员中使用GET或PUT(通过我的API)。
请求(通过Postman):
GET http://localhost:3000/tasks
DE FACTS:
我肯定是连接到数据库的。记录API成功消息后,控制台记录1。
所有版本都兼容。
我已尝试使用3个不同的在线数据库,对所有这些数据库都有这个问题,我肯定做错了。
DA CODE:
服务器文件:
var express = require('express'),
app = express(),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
Task = require('./api/models/model'), //created model loading here
bodyParser = require('body-parser');
// mongoose instance connection url connection
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://<my username>:<mypassword>@groceriescluster-shard-00-00-vaffe.mongodb.net:27017,groceriescluster-shard-00-01-vaffe.mongodb.net:27017,groceriescluster-shard-00-02-vaffe.mongodb.net:27017/test?ssl=true&replicaSet=GroceriesCluster-shard-0&authSource=admin');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var routes = require('./api/routes/routes'); //importing route
routes(app); //register the route
app.listen(port);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
console.log('todo list RESTful API server started on: ' + port);
setTimeout(function(){console.log(mongoose.connection.readyState)},
5000)
控制器:
'use strict';
var mongoose = require('mongoose'),
Task = mongoose.model('Tasks');
exports.list_all_tasks = function(req, res) {
Task.find({}, function(err, task) {
if (err)
res.send(err);
res.json(task);
});
};
exports.create_a_task = function(req, res) {
var new_task = new Task(req.body);
new_task.save(function(err, task) {
if (err)
res.send(err);
res.json(task);
});
};
exports.read_a_task = function(req, res) {
Task.findById(req.params.taskId, function(err, task) {
if (err)
console.log(err);
res.send(err);
res.json(task);
});
};
exports.update_a_task = function(req, res) {
Task.findOneAndUpdate({_id: req.params.taskId}, req.body, {new: true}, function(err, task) {
if (err)
res.send(err);
res.json(task);
});
};
exports.delete_a_task = function(req, res) {
Task.remove({
_id: req.params.taskId
}, function(err, task) {
if (err)
res.send(err);
res.json({ message: 'Task successfully deleted' });
});
};
型号:
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TaskSchema = new Schema({
name: {
type: String,
required: 'Kindly enter the name of the task'
},
Created_date: {
type: Date,
default: Date.now
},
status: {
type: [{
type: String,
enum: ['pending', 'ongoing', 'completed']
}],
default: ['pending']
}
});
module.exports = mongoose.model('Tasks', TaskSchema);
路线:
'use strict';
module.exports = function(app) {
var todoList = require('../controllers/controller');
// todoList Routes
app.route('/tasks')
.get(todoList.list_all_tasks)
.post(todoList.create_a_task);
app.route('/tasks/:taskId')
.get(todoList.read_a_task)
.put(todoList.update_a_task)
.delete(todoList.delete_a_task);
};
package.json
{
"name": "api",
"version": "1.0.0",
"description": "test env api",
"main": "index.js",
"scripts": {
"test": "echo \\\"No time for tests today\\\" && exit1\""
},
"keywords": [
"Here",
"it",
"goes!"
],
"author": "Zack Haigh",
"license": "ISC",
"devDependencies": {
"install": "^0.10.4",
"nodemon": "^1.14.11",
"npm": "^5.6.0"
},
"dependencies": {
"@google-cloud/storage": "^1.5.2",
"body-parser": "^1.18.2",
"express": "^4.16.2",
"mongo": "^0.1.0",
"mongodb": "^2.2.34",
"mongoose": "^5.0.1"
}
}
答案 0 :(得分:1)
我无法查看您的问题,但我可以使用NodeJS
- mongoose
和express
向您显示我的配置。
<强> app.js 强>
var mongoose = require('mongoose')
const { db } = require('./config.js')
mongoose.Promise = global.Promise
var app = express()
mongoose.connect(`mongodb://${db.user}:${db.password}@ds135486.mlab.com:35486/${db.name}`, { useMongoClient: true })
.then(function (info) {
console.log("Conexion MongoDB mlab exitosa...")
}).catch(function (error) {
console.log("Error MongoDB mlab", error)
})
app.use('/', require('./routes/dbtest'))
/*...more code...*/
<强>模型/ Corpus.js 强>
var mongoose = require('mongoose')
var Schema = mongoose.Schema
var Corpus = new Schema({
fecha: Date, //UTC time
compressed: {
type: Boolean,
default: false
}
})
module.exports = mongoose.model('Corpus', Corpus);
<强>路由/ dbtest.js 强>
const router = require('express').Router()
const mongoose = require("mongoose")
const Corpus = require('../models/Corpus.js')
router.get("/corpus", async function (req, res, next){
try {
var docs = await Corpus.find({}, 'fecha compressed').exec()
docs = docs.map(d=> d.toObject()).sort((d1, d2)=> d1.fecha - d2.fecha)
res.json(docs)
} catch (e) { next(e) }
})
module.exports = router;
答案 1 :(得分:1)
这让我很困惑:
var routes = require('./api/routes/routes'); //importing route
routes(app); //register the route
据我所知,在Express.js v.4中,在服务器中插入路由的方式是这样的:
var routes = require('./api/routes/routes'); //importing route
app.use(routes); //register the routes
我会以这种方式定义路线,因此您不必使用app作为参数的函数:
var express = require('express');
var todoList = require('../controllers/controller');
var router = express.Router();
// todoList Routes
router.route('/tasks')
.get(todoList.list_all_tasks)
.post(todoList.create_a_task);
router.route('/tasks/:taskId')
.get(todoList.read_a_task)
.put(todoList.update_a_task)
.delete(todoList.delete_a_task);
module.exports = router;
在服务器文件中使用它们:
var routes = require('./api/routes/routes'); //importing route
app.use(routes); //register the routes
如果你试图使用app.router
,它会在Express.js v.3中被遗忘并在升级到第4版时删除