使用 Express、Node 和 Rest 从 AngularJS 发布数据
Posting data from AngularJS with Express, Node and Rest
我是 javascript 堆栈的新手,一直在尝试从 angular 到 mongo 获取表单 post。我能够取回列表,但无法 post.
下面的代码列表正常,但是当我 post 时,它 post 是一个空白记录(而且,即使我不这样做,它也会每隔几分钟保持 posting不要在页面上执行任何操作)
我可以看到它能够调用服务器端方法,但数据没有被传递到持久性。
我知道我在做一些愚蠢的事情,但不确定它是什么。我搜索了整个 google,但没有看到我可以采用的解决方案。任何帮助将不胜感激。
============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
});
非常感谢大家
编辑 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;
您没有正确注册模型,您需要使用 mongoose.Schema
。我很惊讶你没有收到错误。
var mongoose = require('mongoose');
module.exports = mongoose.model('Listing', new mongoose.Schema({
title: String,
subTitle: String
}));
编辑 1:
将您的 save() 调用更改为以下内容:
$scope.createListing = function(){
$scope.listing.$save();
};
编辑3
注册中间件的顺序很重要。您正在注册您的路线,在您的 bodyparser 之前,这是不正确的。您的主体解析器和其他中间件必须在 routes/API.
之前注册
见下文:
/*%%%%% 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);
我是 javascript 堆栈的新手,一直在尝试从 angular 到 mongo 获取表单 post。我能够取回列表,但无法 post.
下面的代码列表正常,但是当我 post 时,它 post 是一个空白记录(而且,即使我不这样做,它也会每隔几分钟保持 posting不要在页面上执行任何操作)
我可以看到它能够调用服务器端方法,但数据没有被传递到持久性。
我知道我在做一些愚蠢的事情,但不确定它是什么。我搜索了整个 google,但没有看到我可以采用的解决方案。任何帮助将不胜感激。
============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
});
非常感谢大家
编辑 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;
您没有正确注册模型,您需要使用 mongoose.Schema
。我很惊讶你没有收到错误。
var mongoose = require('mongoose');
module.exports = mongoose.model('Listing', new mongoose.Schema({
title: String,
subTitle: String
}));
编辑 1:
将您的 save() 调用更改为以下内容:
$scope.createListing = function(){
$scope.listing.$save();
};
编辑3
注册中间件的顺序很重要。您正在注册您的路线,在您的 bodyparser 之前,这是不正确的。您的主体解析器和其他中间件必须在 routes/API.
之前注册见下文:
/*%%%%% 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);