【问题标题】:Angularjs http post request - params are not reaching to serverAngularjs http post请求-参数未到达服务器
【发布时间】:2017-11-01 12:24:36
【问题描述】:

我正在尝试使用 angularjs 创建发布请求。这是我将供应商添加到服务器的代码。

SupplierService.addNewSupplier = function(supplier)  {
    alert (supplier.name);
    alert (supplier.mobile);
    var Indata = {'name': supplier.name, 'mobile': supplier.mobile};
    //var Indata = {'product': $scope.product, 'product2': $scope.product2 };
    var req = {
        url: SupplierURL,
        method: 'POST',
        params: Indata,
        headers: {'Content-Type': 'application/json'}
    };

    //$http.post(SupplierURL, Indata)
    $http(req)
        .then(function(success){
            console.log(success);
            //SupplierList.push({id: data, name: supplier.name, mobile: supplier.mobile});
            supplier.name = "";
            supplier.mobile = "";
        },function (error){
            console.log(error);

            alert ('Supplier add error.');
        });

};

发出请求后,回调来到错误部分,在控制台日志中我可以看到。

{error: true, message: "未能创建供应商。请重试", name: null, mobile: null}

为什么名称和手机无法访问服务器。相同的请求适用于邮递员(api 测试工具)。所以我不认为服务器端代码中可能存在 anu 问题。任何帮助将不胜感激。

【问题讨论】:

  • 在第 9 行使用data 代替paramsparams 用于GET 请求。
  • 尝试使用经典方式:$http.post(yourUrl, Indata);

标签: angularjs


【解决方案1】:

从 $http 文档中可以清楚地看到请求参数:

https://docs.angularjs.org/api/ng/service/$http

var req = {
 method: 'POST',
 url: 'http://example.com',
 headers: {
   'Content-Type': undefined
 },
 data: { test: 'test' }
}

$http(req).then(function(){...}, function(){...});

因此,在您的情况下,您需要将paramsdata 切换:

 var req = {
        url: SupplierURL,
        method: 'POST',
        data: Indata,
        headers: {'Content-Type': 'application/json'}
    };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-21
    • 2016-12-09
    • 1970-01-01
    • 1970-01-01
    • 2017-08-24
    • 1970-01-01
    • 2021-08-08
    • 2019-04-26
    相关资源
    最近更新 更多