【发布时间】:2017-01-05 05:35:06
【问题描述】:
我正在尝试将数据从我的Angular.js 控制器发送到Node.js 后端。提出请求时,我成功创建了MongoDB 条目。但 MongoDB 条目中缺少数据。我被卡住了,无法再继续使用我的应用程序了。谁能给我一个清楚的解释为什么我无法将表单数据发送到Node.js。
我已将数据架构放在这里:
var common = require('../common');
var inviteeSchema = common.Schema({
email: String
});
var Invite = common.conn.model('Invite', inviteeSchema);
module.exports = Invite;
我在这里附上了路由代码。
router.route('/addtoinvitelist').post(function (req, res, next) {
var invite =new Invite(req.body);
invite.save(function(err,email){
if(err) throw err;
res.json({message:"your mail id is stored in our database we will soon send you an invite"})
});
});
我的 HTML 表单放在这里
<form action="#">
<div class="form-group">
<label for="subcribeNewsletter" class="control-label">INVITE FORM<br> <small>We are happy to invite you to medicoshere, So please enter your email ID in the below form.</small></label>
<div class="input-group input-group-in input-group-sm">
<div class="input-group-addon"><i class="fa fa-envelope text-belpet"></i></div>
<input class="form-control" id="subcribeNewsletter" placeholder="name@mail.com" ng-model="useremail" required>
<div class="input-group-btn">
<button type="submit" class="btn btn-default text-belpet" ng-click="AddToInviteList(useremail)"><strong>OK</strong></button>
</div>
</div>
</div><!-- /.form-group -->
</form><!-- /form -->
我的角度服务功能在这里 `this.AddToInviteList = function (email, cb) {
$http({
method: 'POST',
url: "http://localhost:3000/users/addtoinvitelist",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}, // set the headers so angular passing info as form data (not request payload)
data:"email"
}).success(function (data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
}`
控制器功能在这里
App.controller('InviteController', function ($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.init = function () {
console.log("hii this is a test ")
};
$scope.email = {};
$scope.AddToInviteList = function () {
UserServices.AddToInviteList($scope.email, function (dataresponse) {
console.log(dataresponse);
})
}
});
【问题讨论】:
-
您是否在后端获得
email值? -
是的,数据库中有一个空字符串...
-
因为您将静态
email作为字符串发送,所以在正文中使用data:email -
如果我提供数据:电子邮件,那么数据库中没有电子邮件条目,只有对象 ID 进入数据库...
-
您的模型名称是“useremail”,但您将“$scope.email”传递给服务。
标签: angularjs node.js mongodb http multipartform-data