Angular POST to Node Server

Angular POST to Node Server

本文关键字:Server Node to POST Angular      更新时间:2023-09-26

我正在尝试学习角,我遇到了一个问题。我有一个提交项目名称,价格和图像到MongoDB的表单。在我的节点路由中,我使用res.json作为响应。在使用jQuery POST方法时,我可以留在页面上并将数据返回到控制台或变量或其他任何东西。当我改变到角POST方法时,我实际上是要去一个包含JSON响应的新页面。这当然不是我想要的。我想在不离开页面的情况下更新数据库、获取新数据和更新模型。

这是我的节点路由。

router.post('/items/add', function(req, res){
    // handle image upload
    fs.readFile(req.files.image.path, function (err, data) {
        var imageName = req.files.image.name
        /// If there's an error
        if(!imageName){
            console.log("There was an error")
            res.redirect("/");
            res.end();
        } else {
            var newPath = '/uploads/' + imageName;
          /// write file to uploads/fullsize folder
          fs.writeFile(newPath, data, function (err) {
          });
        }
    });
    // save info to database
    var newItem = new Item({
        name : req.param('Name'), 
        price : req.param('Price'),
        image : req.files.image.name
    });
    newItem.save(function(err){
        if(err){
            console.log(err);
        } else{
            Item.find(function(err, items){
                if (err){
                    return console.log(err);
                } else{
                    res.json({
                        items : items
                    });
                }
            });
        }
    });
});

这是我的angular代码

var allItems = angular.module('allItems', []);
allItems.controller('allItemsCtrl', function ($scope, $http) {
    $scope.updateItems = function(){
        $http.get('/allItems').success(function(data){
            $scope.theitems = data.allItems;
        });
    };
    // The culprit
    $scope.postItems = function(){
        $scope.formData = {};
        $http.post('/items/add', formData).success(function(data){
            $scope.theitems = data.allItems;
        });
    };
    $scope.updateItems();
});

数据是正确张贴,但我希望它的行为像一个AJAX帖子,而不是离开页面。我该如何做到这一点?

当你有一个真正的HTML表单,像这样的提交按钮

<form method="post" action="http://yoursite.com/items">
  <input type="text"/>
  <button type="submit">Submit</button>
</form>

,然后它会做一个页面刷新不管你在你的JavaScript中最终做什么。我会保留HTML表单元素,所以它在语义上是正确的,但你不需要方法或动作属性。在你的表单上使用ngSubmit,像这样

<form ng-submit="postItems()">
  <input type="text"/>
  <button type="submit">Submit</button>
</form>