我正在通过this tutorial的方式学习MEAN堆栈。我已经设置了节点服务器并使mongodb成功运行,但是当我通过以下方式测试数据库时:
curl --data 'title=test&link=http://test.com' http://localhost:3000/posts
它给我一个404错误。如果我只是在它发回一个空容器的地址上运行curl。
目前我的代码如下所示:
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 app = express();
var users = require('./routes/users');
var mongoose = require('mongoose');
require('./models/Posts');
require('./models/Comments');
mongoose.connect('mongodb://localhost/Posts');
var routes = require('./routes/index');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
...
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');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', {
title: 'Express'
});
});
router.get('/Posts', function(req, res, next) {
Post.find(function(err, posts) {
if (err) {
return next(err);
}
res.json(posts);
});
});
router.post('/Comments', function(req, res, next) {
var post = new Post(req.body);
post.save(function(err, post) {
if (err) {
return next(err);
}
res.json(post);
});
});
module.exports = router;
我觉得我对javascript的掌握相当不错但是我很难理解为什么这不起作用。感谢您的帮助,这是第一个完全被
困扰的问题