javascript - 为什么我必须将参数作为 $http angular 中的对象发送?

标签 javascript angularjs

我正在制作 CRUD,如果我想将一些数据发送到我的后端 (node.js),那么我会收到一个错误: angular.js:10765 POST http://localhost:1234/shop/removeProduct/574bf938b16158b40f9c87bc 400(错误请求)

脚本:

$scope.removeProduct = function (partnerId, productId) {
    $http.post("/campaign/removeProduct/" + partnerId, productId);
}

解决方案只是简单地将此参数 (productId) 打包到一个对象中,如下所示:

$scope.removeProduct = function (partnerId, productId) {
    $scope.productData = {productId: productId};
    $http.post("/campaign/removeProduct/" + partnerId, $scope.productData);
}

但为什么我必须这样做呢?顺便问一下,这是正确的还是我应该以不同的方式来做?


@编辑 还有一件事,我应该如何在添加/删除任何对象后刷新数据? 这是正确的吗?

$scope.addPartner = function(data) {
$http({method: 'POST', url: addPartner, data})
.then(function(response) {
console.log(response);
});
$scope.loadPartnersData();
window.alert("Partner added!");
};

$scope.loadPartnersData = function () {
$http.get("/campaign/partner-list").then(function(result) {
$scope.partnerList = result.data.partnerList;
});
};

后端:

router.get('/partner-list', function (req, res) {
    Partner.find({}, function (err, partnerList) {
        if (err) throw err;

        res.json({ partnerList: partnerList });
    });
});

最佳答案

我假设您希望 url 类似于 /shop/removeProduct/34523543?productData=5325345。如果是这样,那么我将使用声明 $http 请求的 Angular 方式:

var url = '/shop/removeProduct/' + partnerId; /* How ever you declare this */
$scope.removeProduct = function() {
  $http({method: 'POST', url, params:{'productData': productId}})
    .then(function(response) {
      console.log(response);
    });
};

$scope.removeProduct();

Angular then takes care of the decoding of the parameters

关于javascript - 为什么我必须将参数作为 $http angular 中的对象发送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37539461/

相关文章:

javascript - 如何使用 JQuery 按属性删除元素

javascript - jQuery - 如何动态添加到列表元素

javascript - “Thinking in ReactJS",如果我有AngularJS背景?

javascript - 如何从 HTML 访问 CSV 文件并将其保存在数组中(仅使用 Javascript)

javascript - jQuery 点击关闭元素事件

javascript - map API 不适用于 HTML 中的 Windows Phone

JavaScript 的固执

angularjs - 使用 AngularUI Bootstrap Modal 的 AngularJS 中的范围问题

angularjs - 在编译阶段完成的 DOM 操作运行一次,并始终传播 - 这意味着什么

angularjs - Angular 与微数据