在Thinkster MEAN Stack Tutorial中的API调用404

时间:2016-12-30 23:23:16

标签: express mean-stack

我跟随this Thinkster tutorial关于使用MEAN构建一个reddit-esque网络应用程序。

本教程指示使用curl创建新帖子。

  

C:\root>curl --data "title=test&link=http://test.com" http://localhost:3000/posts

但是,我在回复时收到此错误:

<h1>Not Found</h1>
<h2>404</h2>
<pre>Error: Not Found
    at C:\root\app.js:30:13
    at Layer.handle [as handle_request] (C:\root\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\root\node_modules\express\lib\router\index.js:312:13)
    at C:\root\node_modules\express\lib\router\index.js:280:7
    at Function.process_params (C:\root\node_modules\express\lib\router\index.js:330:12)
    at next (C:\root\node_modules\express\lib\router\index.js:271:10)
    at C:\root\node_modules\express\lib\router\index.js:618:15
    at next (C:\root\node_modules\express\lib\router\index.js:256:14)
    at Function.handle (C:\root\node_modules\express\lib\router\index.js:176:3)
    at router (C:\root\node_modules\express\lib\router\index.js:46:12)</pre>

我仔细查看了这些文件,但所有参考资料都只是告诉我错误会发生什么......

这里有一些代码

/routes/index.js:

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = 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);
    })
})

/models/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);

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 index = 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');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
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 handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

var mongoose = require('mongoose');
require('./models/Posts');
require('./models/Comments');

mongoose.connect('mongod:localhost/news');

我觉得我做的一切都是正确的,除了我不确定将其他路线放在路线索引文件中的位置,同样在app.js中。但这对我来说似乎微不足道。我执行了我能想到的所有调试但是卡住了。

还应该注意,本教程可能不适合在Windows机器上使用。我必须安装curl并做一些在Linux或Mac上可能不需要的其他事情。我使用的是Windows 10。

1 个答案:

答案 0 :(得分:1)

您的module.exports routes / index.js 中过早调用。将module.exports = router;移至文件底部,回收您的服务,然后重试。

app.js 也存在问题。见下文:

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');

// Notice the differences starting here
var app = express();

var mongoose = require('mongoose');

// connect MongoDB
mongoose.connect('mongodb://localhost/news', function(err,db){
    if (!err){
        console.log('Connected to /news!');
    } else{
        console.dir(err); //failed to connect
    }
});

require('./models/Posts');
require('./models/Comments');

var index = require('./routes/index');
var users = require('./routes/users');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
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 handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});


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){ 
            alert(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){ 
            alert(err);
            return next(err); 
        }

        res.json(post);
    })
})

module.exports = router;