簡體   English   中英

MEAN堆棧-GET和POST不查詢或保存到mongodb

[英]MEAN stack - GET and POST not querying or saving to mongodb

我的路線和使用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!' });
      }
    });
});

如果沒有特定的輸出顯示出問題所在,那么這里有一些事情需要我做。 第一個並不總是使用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版本,您可能會在發布請求中使用不建議使用的promise語法。 您應該使用.then(),而不是.success()和.error()。 這也可能引起問題。

最后,您應該盡最大努力遵循REST准則進行路由和響應。 這將使擴展Web應用程序變得更加容易,並使您更有條理。 這是https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4的一個很好的Express / Node資源。

添加:這是一個如何根據生產/開發環境記錄錯誤的示例

// 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: {}
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM