繁体   English   中英

AngularJS将数据发布到nodeJs / Sequelize

[英]AngularJS post Data to nodeJs/Sequelize

我正在使用Nodejs / Sequelize和AngularJs创建一个电子商务网站。

我实际上有这个启动器AngularJS starter

在我的项目中,我有2个文件夹:

  • 客户端(包含AngularJS入门文件夹)

客户端文件夹

  • 服务器(包含我的server.js

服务器文件夹

我想注册一个用户,我的“ registeredView.html”格式如下:

<form ng-submit="submit()">
            <input type="text" name=firstname ng-model="user.firstname" placeholder="firstname" required=" ">
            <input type="text" name="lastname" ng-model="user.lastname" placeholder="lastname" required=" ">
            <input type="email" name="email" ng-model="user.email" placeholder="Email Address" required=" ">
            <input type="password" name="password" ng-model="user.password" placeholder="Password" required=" ">
            <input type="password" name="confirm_password" ng-model="user.confirm_password" placeholder="Password Confirmation" required=" ">
            <input type="submit" value="Register">
        </form>

现在,借助$ scope.user,我可以在“ RegisteredController”中获取这些数据,但是我不知道如何将这些数据发送到服务器。

我正在使用express模块​​,所以我尝试使用$ http.post这样的:

    .controller('RegisteredController', ['$scope', function ($scope, $http) {
    $scope.submit = function () {
        $http.post('/registered', $scope.user)
        then(function (response) {
            console.log("posted")
        }).catch(function (response) {
            console.error(response)
        })
    }
}]);

在我的“ server.js”上,我试图得到这样的帖子:

app.get('/registered', function (req, res) {
console.log(req.body)
res.end();

});

但这不起作用..

我错了吗? 一些忠告 ? 我需要你们的帮助:)

正如评论中所讨论的,存在3个直接显而易见的问题:

  • 您的服务器希望get一个get而不是一个post ,将app.get('/registered'...)更改为app.post('/registered'...)

  • 您在这里缺少点: $http.post('/registered', $scope.user)then(function (response) { ,在结束之间) then

  • 您需要像$scope一样标记要注入的$http['$scope', function ($scope, $http)更改为['$scope', '$http', function ($scope, $http)

为了能够处理您发布的数据,您应该检出主体解析器 要求之后,您可以执行以下操作app.use(bodyParser.json()) 然后,您应该可以访问req.body ,其中应该包含被解析为javascript对象的用户。

暂无
暂无

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

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