MEAN堆栈 - GET和POST不查询或保存到mongodb

时间:2016-08-06 04:21:52

标签: angularjs mongodb express mongoose mean-stack

我的路线和使用mongodb获取/保存数据时遇到问题。保存或未发布JSON时似乎存在验证错误。有什么想法吗?

这是我的猫鼬模式:

// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// create a schema
var sitesEntrySchema = new Schema({
    ip: {
      type: String,
      required: true,
      trim: true
    },
    domain: {
      type: String,
      required: true,
      trim: true
    },
    wp: {
      type: String,
      required: true,
      trim: true
    },
    host_name: {
      type: String,
      required: true
    },
    hosted: {
      type: Number,
      required: true
    }
});

// make this available to our users in our Node applications
var Site = mongoose.model('Site', sitesEntrySchema);
module.exports = Site;

我的角度http请求

var app = angular.module('myApp', []);

app.controller('MainCtrl', function($scope, $http) {
    $http.get('/api/mongo')
    .then(function(response) {
        console.log(response.data);
        $scope.myData = response.data;
    });
});

app.controller('FormCtrl', function($scope, $http) {
    $scope.formData = {};

    $scope.addSite = function() {
        $http.post('/api/create', $scope.formData)
            .success(function(data) {
                console.log($scope.formData);
                $scope.formData = {}; // clear the form so our user is ready to enter another
                swal(
                  'Good job!',
                  'Site was added!',
                  'success'
                );
            })
            .error(function(data) {
                console.log('Error: ' + data);
            });
    };
});

我的快递路线:

var express = require('express');
var router = express.Router();
var Site = require('../models/site');

//Return From Mongo
router.get('/api/mongo', function(req, res) {
  Site.find({}, function(err, sites) {
    if (err)
      res.send(err)
    res.send(sites);
  });
  //res.json({"yo": "yo this shit works"});
});

//Add A Site 
router.post('/api/create', function(req, res, next) {
    //create object with form input
    var siteData = {
      ip: req.body.ip, 
      domain: req.body.domain, 
      wp: req.body.wp, 
      host_name: req.body.host_name, 
      hosted: req.body.hosted
    };

    // use schema's 'create' method to insert doc into mongo
    Site.create(siteData, function(error) {
      if (error) {
        //return next(error);
        res.send(error);
      } else {
        return res.json({ message: 'Site added!' });
      }
    });
});

1 个答案:

答案 0 :(得分:0)

如果没有显示出现问题的具体输出,这里有一些事情可以解决。第一个并不总是响应json。您还应该尝试使用next()来处理错误,因为Express会确保发回正确的错误响应。通过这些更改,您的获取路径如下:

//Return From Mongo
router.get('/api/mongo', function(req, res, next) {
  Site.find({}, function(err, sites) {
    if (err) {
      next(err)
    } else {
      return res.json(sites);
    }
  });

});

其次,最佳做法是返回新创建的资源,因此您的创建路径应该看起来像

//Add A Site 
router.post('/api/create', function(req, res, next) {
    //create object with form input
    var siteData = {
      ip: req.body.ip, 
      domain: req.body.domain, 
      wp: req.body.wp, 
      host_name: req.body.host_name, 
      hosted: req.body.hosted
    };

    // use schema's 'create' method to insert doc into mongo
    Site.create(siteData, function(error, site) {
      if (error) {
        next(error);
      } else {
        return res.json(site);
      }
    });
});

此外,根据您的Angular版本,您可能会对post请求使用不推荐的promise语法。你应该使用.then(),而不是.success()和.error()。这也可能导致问题。

最后,您应该尽量遵循针对路线和响应的REST指南。它将使您的Web应用程序扩展变得更加容易,并使您更有条理。这是https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4的一个很好的Express / Node资源。

ADDED:以下是根据生产/开发环境记录错误的示例

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    console.log('err:', err.status, err.message);
    res.status(err.status || 500);
    res.json({message: err.messages});
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});