简体   繁体   English

使用Express,Node和Rest从AngularJS发布数据

[英]Posting data from AngularJS with Express, Node and Rest

I am quite new to the javascript stack and have been trying to get a form post from angular onto to mongo. 我对javascript堆栈很陌生,一直在尝试将表格发布从angular转移到mongo。 I am able to get a list back, but not able to post. 我可以重新获得列表,但无法发布。

The below code lists ok, but when I post, it posts a blank record (and moreover, it keeps posting every couple of minutes even though I don't do any action on the page) 下面的代码列出了,但是,当我发布时,它发布了一个空白记录(而且,即使我没有对该页面执行任何操作,它也会每隔几分钟发布一次)

I can see that its able to call the Server side method, but the data is not being passed on towards persistence. 我可以看到它能够调用服务器端方法,但是数据并没有传递给持久性。

I know I am doing something stupid, but just not sure what it is. 我知道我在做一些愚蠢的事情,但是只是不确定那是什么。 I've searched all over google, but don't see the solution which I can take. 我已经在整个Google上进行了搜索,但是看不到可以采取的解决方案。 Any help would be greatly appreciated. 任何帮助将不胜感激。

============jade================
    div(ng-app="sell" ng-controller="sellCtlr")
        .container-fluid
        form#listingForm.form-horizontal
                      .form-group
                       .row
                           .col-xs-8
                               label.control-label(for="title") title 
                               input#title.form-control(type="text", name="title", ng-model="listing.title")
                   .form-group
                       .row
                           .col-xs-8
                               label.control-label(for="subTitle") sub-title
                               input#subTitle.form-control(type="text", name="subTitle",, ng-model="listing.subTitle")

  .........
  .........
                        .form-group
                       .col-xs-6
                           button.btn.btn-primary(type="submit" ng-click="createListing()") Submit
============app.js================
/* server side controllers **/
var listController = require('./server/controllers/list-controller');

/* routes */
var sell = require('./client/routes/sell');

/* rest api */
app.get('/api/listings', listController.list);
app.post('/api/listings', listController.create);

/* sell route */
app.use('/sell', sell);

============sell.js (sell route)================
var express = require('express');
var router = express.Router();

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

/* POST sell page. */
router.post('/api/listings', function(req, res, next) {
    res.render('sell', { title: 'Express' });
});

module.exports = router;

============sellCtlr.js (client side)================    

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

app.controller('sellCtlr', ['$scope', '$resource',
    function($scope, $resource){

    var Listing = $resource('/api/listings');
    $scope.listing = new Listing();

    $scope.createListing = function(){

        Listing.save($scope.listing, function(){
            //data saved. do something here.
        });//saves an entry. Assuming $scope.listing is the Listing object
        };
    }]);

============list-controller.js (server side)================

var Listing = require('../models/listing');

// save listing
module.exports.create = function (req, res) {
  var listing = new Listing(req.body);
  listing.save(function (err, result){
      res.json(result);
  });
}
//retrieve all listings
module.exports.list = function(req, res){
Listing.find({}, function(err, results) {
    res.json(results);
});
}


============listing.js (model, server side)================

var mongoose = require('mongoose');

module.exports = mongoose.model('Listing', {
  title: String,
  subTitle: String

});

Many Thanks guys 非常感谢你们

EDIT 2 -- FULL app.js file 编辑2-完整的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');

/*%%%%% server side controllers %%%%%%**/
var listController = require('./server/controllers/list-controller');
/*%%%%% server side controllers %%%%%%**/


/*%%%%% mongoose config %%%%%%**/
var secrets = require('./config/secrets');
var mongoose = require('mongoose');
//Connect to the MongoDB
mongoose.connect(secrets.db);
/*%%%%% mongoose config %%%%%%**/

/*%%%%% routes %%%%%%**/
var index = require('./client/routes/index');
var listing = require('./client/routes/listing');
var users = require('./client/routes/users');
var sell = require('./client/routes/sell');
/*%%%%% routes %%%%%%**/

/*%%%%% express setup %%%%%%**/
var app = express();
/*%%%%% express setup %%%%%%**/

/*%%%%% view engine setup %%%%%%**/
app.set('views', path.join(__dirname, 'client/views'));
app.set('view engine', 'jade');
/*%%%%% view engine setup %%%%%%**/

/*%%%%% client side directories %%%%%%**/
app.use(express.static('client'));
app.use(express.static('client/views'));

app.use('/js', express.static(__dirname + '/client/js'));
app.use('/js', express.static(__dirname + '/client/views/js'));

app.use('/css', express.static(__dirname + '/client/views/css'));

/*%%%%% rest api's %%%%%%**/
app.get('/api/listings', listController.list);
app.post('/api/listings', listController.create);
/*%%%%% rest api's %%%%%%**/



// 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);
app.use('/sell', sell);

// 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 handlers

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

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


module.exports = app;

You aren't registering the model correctly, you need to use mongoose.Schema . 您没有正确注册模型,需要使用mongoose.Schema I'm surprised you aren't getting an error. 我很惊讶您没有出错。

var mongoose = require('mongoose');

module.exports = mongoose.model('Listing', new mongoose.Schema({
  title: String,
  subTitle: String
}));

EDIT1: EDIT1:

Change your save() call to the following: 将您的save()调用更改为以下内容:

$scope.createListing = function(){
  $scope.listing.$save();
};

EDIT3 EDIT3

The order in which you register your middleware matters. 注册中间件的顺序很重要。 You are registering your routes, before your bodyparser, this is not correct. 您在bodyparser之前注册路线,这是不正确的。 Your body parser, and other middleware must be registered BEFORE the routes/API. 必须在路由/ API之前注册您的正文解析器和其他中间件。

See below: 见下文:

/*%%%%% express setup %%%%%%**/
var app = express();
/*%%%%% express setup %%%%%%**/

/*%%%%% view engine setup %%%%%%**/
app.set('views', path.join(__dirname, 'client/views'));
app.set('view engine', 'jade');
/*%%%%% view engine setup %%%%%%**/

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


// ***Register the API AFTER the body and cookie parser**

/*%%%%% client side directories %%%%%%**/
app.use(express.static('client'));
app.use(express.static('client/views'));

app.use('/js', express.static(__dirname + '/client/js'));
app.use('/js', express.static(__dirname + '/client/views/js'));

app.use('/css', express.static(__dirname + '/client/views/css'));

/*%%%%% rest api's %%%%%%**/
app.get('/api/listings', listController.list);
app.post('/api/listings', listController.create);
/*%%%%% rest api's %%%%%%**/

app.use('/', index);
app.use('/users', users);
app.use('/sell', sell);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM