2016-05-24 2 views
2

Я создаю приложение в NodeJS/Express в сочетании с Mongodb, где я хочу, чтобы иметь возможность комментировать сообщение, но я продолжаю получать 404 не найден.Не может POST (комментарий к сообщению) | Mongodb with mongoose

I Настройка модели и маршруты в моих server.js, а также настроить «ссылка» между ними, но это ответ, который я получаю:

Post Request И как вы можете видеть в последующем, «захват» ака «пост» действительно существует:

capture

Edit: Внесены некоторые изменения в свой исходный код с ответами, которые Zen мне дали.

Это мой код:

-server.js

// Init Express Web Framework 
var express = require('express'); 
var app = express(); 
var path = require('path'); 


// Set view engine to EJS & set views directory 
app.engine('html', require('ejs').renderFile); 
app.set('view engine', 'html'); 
app.set('views', path.resolve(__dirname, 'client', 'views')); 

app.use(express.static(path.resolve(__dirname, 'client'))); 

// Database Connection 
var mongoose = require('mongoose'); 
var configDB = require('./server/config/database.js'); 
require('./server/routes/capture'); 
require('./server/routes/comment'); 
mongoose.connect(configDB.url); 

var bodyParser = require('body-parser'); 
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({extended: true}));    
app.use(bodyParser.text());          
app.use(bodyParser.json({ type: 'application/json'})); 

// Main route 
app.get('/', function(req, res){ 
    res.render('index.html'); 
}); 
// API 
var api = express.Router(); 
require('./server/routes/capture')(api); 
require('./server/routes/comment')(api); 
app.use('/api', api); 

// Port Settings 
app.listen(process.env.PORT || 3000, process.env.IP); 
console.log('Listening on port ' + process.env.PORT); 

-capture.js модель:

var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 
var captureSchema = Schema({ 
    birdname: {type: String, required: true}, 
    place: String, 
    userId: String, 
    author: String, 
    picture: Schema.Types.Mixed, 
    created_at: Date, 
    comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment'}] 
}); 

module.exports = mongoose.model('Capture', captureSchema); 

-capture.js маршрута:

var Capture = require('../models/capture'); 

module.exports = function(router) { 
    router.post('/captures', function(req, res){ 
     var capture = new Capture(); 
     capture.birdname = req.body.birdname; 
     capture.place = req.body.place; 
     capture.userId = req.body.userId; 
     capture.author = req.body.author; 
     capture.picture = req.body.picture; 
     capture.created_at = new Date(); 


     capture.save(function(err, data){ 
      if(err) 
       throw err; 
      console.log(req.body); 
      res.json(data); 
     }); 
    }); 

    router.get('/captures', function(req, res){ 
     Capture.find({}, function(err, data){ 
      if(err) 
       throw err; 
      res.json(data); 
     }); 
    }); 

    router.delete('/captures', function(req, res){ 
      Capture.remove({}, function(err){ 
       res.json({result: err ? 'error' : 'ok'}); 
      }); 
     }); 

    router.get('/captures/:id', function(req, res){ 
     Capture.findOne({_id: req.params.id}, function(err, data){ 
      if(err) 
       throw err; 
      res.json(data); 
     }); 
    }); 

    router.delete('/captures/:id', function(req, res){ 
     Capture.remove({_id: req.params.id}, function(err){ 
      res.json({result: err ? 'error' : 'ok'}); 
     }); 
    }); 
}; 

-capture.js модель:

var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 
var commentSchema = Schema({ 
    birdname: String, 
    body: {type: String, required: true}, 
    userId: {type: String, required: true}, 
    author: {type: String, required: true}, 
    created_at: Date, 
    capture: [{ type: Schema.Types.ObjectId, ref: 'Capture'}] 
}); 

module.exports = mongoose.model('Comment', commentSchema); 

-comment.js маршрут:

var Comment = require('../models/comment'); 

module.exports = function(router) { 
    router.post('/captures/:capture/comments', function(req, res, next){ 
     var comment = new Comment(); 
     comment.birdname = req.body.birdname; 
     comment.body = req.body.body; 
     comment.userId = req.body.userId; 
     comment.author = req.body.author; 
     comment.created_at = new Date(); 
     comment.capture = capture; 

     comment.save(function(err, comment) { 
      if (err) { return next(err); } 

      req.capture.comments.push(comment); 
      req.capture.save(function(err, capture) { 
       if (err) { return next(err); } 

       res.json(comment); 
      }); 
     }); 
    }); 
}; 

Любая помощь очень ценится .. Благодаря

ответ

1

Я работал бы с одним сценарием маршрута, видя, что ваши комментарии прикреплены к сообщению. Вам также необходимо добавить логику карты в параметры маршрута для зависания и комментариев.

Попробуйте следующее:

var Capture = require('../models/capture'); 
var Comment = require('../models/comment'); 

module.exports = function(router) { 
    router.post('/captures', function(req, res){ 
     var capture = new Capture(); 
     capture.birdname = req.body.birdname; 
     capture.place = req.body.place; 
     capture.userId = req.body.userId; 
     capture.author = req.body.author; 
     capture.picture = req.body.picture; 
     capture.created_at = new Date(); 


     capture.save(function(err, data){ 
      if(err) 
       throw err; 
      console.log(req.body); 
      res.json(data); 
     }); 
    }); 

    router.get('/captures', function(req, res){ 
     Capture.find({}, function(err, data){ 
      if(err) 
       throw err; 
      res.json(data); 
     }); 
    }); 

    router.delete('/captures', function(req, res){ 
      Capture.remove({}, function(err){ 
       res.json({result: err ? 'error' : 'ok'}); 
      }); 
     }); 

    // Map logic to route parameter 'capture' 
    router.param('capture', function(req, res, next, id) { 
     var query = Capture.findById(id); 

     query.exec(function (err, capture) { 
      if (err) { return next(err); } 
      if (!capture) { return next(new Error("can't find post")); } 

      req.capture = capture; 
      return next(); 
     }); 
    }); 
    // Map logic to route parameter 'comment' 
    router.param('comment', function (req, res, next, id) { 
     var query = Comment.findById(id); 

     query.exec(function (err, comment) { 
      if (err) { return next(err); } 
      if (!comment) { return next(new Error("can't find comment")); } 

      req.comment = comment; 
      return next(); 
     }); 
    }); 

    router.get('/captures/:id', function(req, res){ 
     Capture.findOne({_id: req.params.id}, function(err, data){ 
      if(err) 
       throw err; 
      res.json(data); 
     }); 
    }); 

    router.delete('/captures/:id', function(req, res){ 
     Capture.remove({_id: req.params.id}, function(err){ 
      res.json({result: err ? 'error' : 'ok'}); 
     }); 
    }); 

    router.post('/captures/:capture/comments', function(req, res, next){ 
     var comment = new Comment(); 
     comment.birdname = req.body.birdname; 
     comment.body = req.body.body; 
     comment.userId = req.body.userId; 
     comment.author = req.body.author; 
     comment.created_at = new Date(); 
     comment.capture = req.capture; 

     comment.save(function(err, comment) { 
      if (err) { return next(err); } 

      req.capture.comments.push(comment); 
      req.capture.save(function(err, capture) { 
       if (err) { return next(err); } 

       res.json(comment); 
      }); 
     }); 
    }); 
}; 
+1

Спасибо! Это сделал трюк. – Pex

0

код состояния - 404. По-видимому, никакой соответствующий маршрут er. Проблема заключается в том, что вы экспортируете функцию «init» в comment.js route. Когда вам нужен маршрутизатор комментариев в server.js, ничего не происходит.

// API 
var api = express.Router(); 
require('./server/routes/capture')(api); 
// you have forgotten it 
require('./server/routes/comment')(api); 
app.use('/api', api); 

BTW, нет необходимости положить capture в req.body, когда Вы отправляете в '/captures/:capture/comments', так как вы можете получить :capture с помощью const capture = req.params.capture;.

+0

Это все еще дает 404. Я буду обновлять код (в OP) с теми, у отдавших – Pex

+0

После повторного глядя на мой код, я имею в виду, что проблема заключается в пути comment.js. Но я не уверен, как его решить. Я думаю, что проблема заключается в этом разделе: 'req.capture.comments.push (комментарий); req.capture.save (функция (err, capture) { если (ошибка) {возврат следующий (ошибка);} res.JSON (комментарий); }); 'так, что комментарий не может найти захват? – Pex

 Смежные вопросы

  • Нет связанных вопросов^_^