【问题标题】:AngularJS post Data to nodeJs/SequelizeAngularJS 将数据发布到 nodeJs/Sequelize
【发布时间】:2018-02-09 05:09:48
【问题描述】:

我正在使用 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();

});

但它不起作用..

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

【问题讨论】:

    标签: javascript angularjs node.js express sequelize.js


    【解决方案1】:

    正如 cmets 中所讨论的,有 3 个显而易见的问题:

    • 您的服务器需要 get,而不是 post,请将 app.get('/registered'...) 更改为 app.post('/registered'...)

    • 您在此处缺少一个点:$http.post('/registered', $scope.user)then(function (response) {,位于结尾的 )then 之间。

    • 您需要将$http 标记为要注入,就像$scope - 将['$scope', function ($scope, $http) 更改为['$scope', '$http', function ($scope, $http)

    为了能够对您发布的数据做一些事情,您应该查看body parser。要求后,您可以执行以下操作 - app.use(bodyParser.json())。然后你应该可以访问req.body,它应该包含你的用户被解析为一个javascript对象。

    【讨论】:

    • 是的,我刚刚注意到它并尝试更改为 app.post 但它仍然无法正常工作
    • 你在这里少了一个点:$http.post('/registered', $scope.user)then(function (response) {,在结束 )then 之间。如果这对您没有帮助,您将不得不更具体地告诉我们什么不起作用,是否有错误?
    • 即使我在app.post request.body中得到了数据,我该如何处理数据?
    • @UncleDava 糟糕,无法解决这个问题
    • @UncleDava 我修复了它并得到 TypeError: Cannot read property 'post' of undefined
    猜你喜欢
    • 2018-10-14
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    相关资源
    最近更新 更多