我正在尝试使用net中的以下代码访问MongoDB,但是当我尝试访问该URL时,它说
Cannot GET /posts?title=test&link=http://test.com
当我试图像这样使用它时
http://localhost:3000/posts?title=test&link=http://test.com
我的app.js:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/news');
require('./models/Posts');
require('./models/Comments');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
module.exports = app;
和index.js:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Post = mongoose.model('Post');
var Comment = mongoose.model('Comment');
router.get('/posts', function(req, res, next) {
Post.find(function(err, posts) {
if (err) { return next(err); }
res.json(posts);
});
});
router.post('/posts', function(req, res, next) {
var post = new Post(req.body);
post.save(function(err, post) {
if (err) { return next(err); }
res.json(post);
});
});
Posts.js:
var mongoose = require('mongoose');
var PostSchema = new mongoose.Schema({
title: String,
link: String,
upvotes: { type: Number, default: 0 },
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
});
mongoose.model('Post', PostSchema);
Comments.js:
var mongoose = require('mongoose');
var CommentSchema = new mongoose.Schema({
body: String,
author: String,
upvotes: { type: Number, default: 0 },
post: { type: mongoose.Schema.Types.ObjectId, ref: 'Post' }
});
mongoose.model('Comment', CommentSchema);
答案 0 :(得分:0)
你的问题与mongodb无关,但是你错过了两个明确的特定点:
1)您需要将index.js
添加到快递应用中,执行类似app.use('/', require('./routes/index'))
的操作。
2)您需要在index.js
中导出路由器。