ПОМЕЩЕНИЕ и УДАЛЕНИЕ - RESTful API Express MongoDB Mongoose

Первый раз публикую. Я создаю сайт блога и использую Node.js, Express.js, MongoDB и Mongoose для своей серверной части. GET и POST работают для получения и создания сообщений. Однако PUT и DELETE не работают при использовании POSTMAN, так как я получаю сообщение «Невозможно DELETE (PUT) /api/blog». Я чувствую, что это связано с маршрутами, особенно когда я пытаюсь найтиById (/api/blog/:blog_id).

Сервер.js

  var express = require('express');
  var mongoose = require('mongoose');
  var port = process.env.PORT || 8080;
  var logger = require('morgan');
  var favicon = require('serve-favicon');
  var bodyParser = require('body-parser');
  var methodOverride = require('method-override');
  var app = express();

  mongoose.connect('mongodb://127.0.0.1:27017/blog');

  var db = mongoose.connection;

  db.on('error', console.error.bind(console, 'connection error: '));
  db.once('open', function callback () {
    console.log("Scrolls are ready to be written!!!");
  });

  app.use(logger('dev'));
  app.use(bodyParser.json());
  app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(bodyParser.text());
  app.use(methodOverride());
  app.use(express.static(__dirname + '/client'));
 app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT, HEAD, DELETE');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, content-type, Accept');
  next();
  });

// *Routes*
  require('./app/routes.js')(app);

// *App Start*
  // http://localhost:8080
  app.listen(port);
  console.log('Connected to port ' + port);
  exports = module.exports = app;

приложение /routes.js

var Blog = require('./models/blog');


    module.exports = function(app) {

        // *Server Routes*
        // Place API calls here
        // Place Authentication routes here
        //var express = require('express');
        //var router = express.Router();
        // *API Routes*
        // Uses Mongoose to GET all Blog Posts from database

        app.get('/api/blog', function(req, res, next) {
            Blog.find(function(err, blog) {
                // If error
                if (err) return next(err);
                  //res.send(err);
                  res.json(blog);
            });
        });

        // Uses Mongoose to POST new Blog Posts in database
        app.post('/api/blog', function(req, res) {
          Blog.create({
            title: req.body.title,
            body: req.body.body,
            author: req.body.author,
            comments: req.body.comments,
            likes: req.body.likes,
            dislikes: req.body.dislikes,
            image: req.body.image,
            createdOn: req.body.createdOn
          }, function(err, blog) {
            if (err)
              res.send(err);
            Blog.find(function(err, blog) {
              if (err)
                res.send(err)
                res.json({ message: 'Blog Post Created!' });
            });
          });
        });

        // Uses Mongoose to GET Blog Post by _id from database
        app.get('/blog/:blog_id', function(req, res) {
          Blog.findById(req.params.blog_id, function(err, blog) {
            if (err)
              res.send (err);
              res.json(blog);
          });
        })

        // Uses Mongoose to PUT updates for Blog Posts by _id in database
        app.put('/blog/:blog_id', function(req, res) {
            Blog.findById(req.params.blog_id, function (err, blog) {
              if (err) res.send(err);

              if (req.body.title) blog.title = req.body.title;
              if (req.body.body) blog.body = req.body.body;
              if (req.body.author) blog.author = req.body.author;
              if (req.body.comments) blog.comments = req.body.comments;
              if (req.body.likes) blog.likes = req.body.likes;
              if (req.body.dislikes) blog.dislikes = req.body.dislikes;
              if (req.body.image) blog.image = req.body.image;
              if (req.body.createdOn) blog.createdOn = req.body.createdOn;

              blog.save( function (err) {
                if (err) send (err);
                res.json({message: 'Blog Post Updated!'});
              });
            });
          });

        // Uses Mongoose to DELETE Blog Posts by _id in database
        app.delete('/blog/:blog_id', function(req, res) {
            Blog.remove({
              _id: req.params.blog_id
            }, function (err, blog) {
              if (err) return res.send(err);
              res.json({ message: 'Blog Post Deleted'});
            });
          });


        // API's for PUT, POST, DELETE go here

        // *Frontend Routes*
        // Route to handle all AngularJS requests

        app.get('*', function(req, res) {
        res.sendfile('./client/views/index.html');
        });

    };

person CaptStarman    schedule 09.12.2015    source источник
comment
Ваш PUT, DELETE, GET по идентификатору '/blog/:blog_id' не '/api/blog/:blog_id'   -  person somallg    schedule 09.12.2015
comment
Решил мою проблему спасибо!   -  person CaptStarman    schedule 09.12.2015