简体   繁体   English

Angular POST to API不传递数据

[英]Angular POST to API doesn't pass data

So I am using makoframework and AngularJS for my project and currently having some problems. 所以我在我的项目中使用makoframework和AngularJS,目前遇到了一些问题。

So in my table customers , the customer_name field is not nullable. 因此,在我的表customerscustomer_name字段不可为空。 My current code where I get all the data from customers table is this. 我从customers表中获取所有数据的当前代码是这样的。

function CustomerCtrl($scope, Customers, DTOptionsBuilder) {
   $scope.loadCustomers = function () {
        Customers.getCustomers()
            .then(function (response) {
                $scope.customers = response.data;
            }, function (error) {
                console.log(error);
            });
    }
}

//factory

function Customers($http) {
  return {
        getCustomers: function () {
            return $http.get('/api/customers');
  },
        addCustomer: function (data) {
                return $http({
                    method: 'POST',
                    url: '/api/customers',
                    data: data
                });
            }
}

The /api/customers returns a json response and it works well with my angular code. /api/customers返回一个json响应,它适用于我的角度代码。

Now I have another route in my php which is /api/products POST and when I try adding data using Advanced Rest Client of Chrome.. it also works. 现在我在我的php中有另一条路线是/api/products POST ,当我尝试使用Chrome的Advanced Rest Client添加数据时......它也有效。

But then when using with my angular code, it doesnt work already. 但是当使用我的角度代码时,它已经不起作用了。

My code 我的代码

    $scope.addCustomer = function () {
           alert($scope.customerData.full_name); // THIS ALERT IS WORKING
            var data = {
                'name': $scope.customerData.full_name,
            }
            Customers.addCustomer(data)
                .then(function (response) {
                    $scope.customerSpinner = true;
                    var message = response.data.message;
                    console.log(response);
                    $scope.customerData = {};
                    $scope.loadCustomers();
                    Materialize.toast('<i class="mdi-navigation-check left"></i> ' + message, 3000, 'green darken-2 white-text');
                }, function (error) {
                    console.log(error);
                });
    }

// HTML // HTML

   <div id="addCustomerModal" class="modal">
        <div class="modal-content">
            <h4>Add Customer</h4>
            <div class="row">
                <form action="" class="col s12">
                    <div class="input-field col s6">
                        <input id="full_name" type="text" class="validate" ng-model="customerData.full_name">
                        <label for="full_name">Full Name</label>
                    </div>
                </form>
            </div>
        </div>
        <div class="modal-footer">
            <a class="waves-effect btn-flat teal lighten-2 white-text" ng-click="addCustomer()">Submit <i class="mdi-content-send right"></i></a>
        </div>
    </div>

// /api/products // /api/products

$routes->post('/api/customers', 'app\controllers\CustomerController::create');
    public function create()
    {
        // take note that this works using a restful client from chrome
        $customer = new Customer();
        $customer->customer_name = $this->request->post('name');

        if($customer->save()) {
            $result = array('success' => true, 'message' => 'Customer '.$this->request->post('name').' has been added.');
        }
        else {
            $result = array('success' => false, 'message' => 'Error adding customer.');
        }
        return $this->jsonResponse($result);
    }

As you can see in the addCustomer $scope , I added an alert($scope.customerData.full_name); 正如您在addCustomer $scope看到的,我添加了一个alert($scope.customerData.full_name); and it actually works. 它确实有效。 I get the data. 我得到了数据。

But I get an SQL error saying 但我得到一个SQL错误说

"SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'customer_name' cannot be null"

Which means the data is not passed to the API though it works when I am using a REST Client from Chrome. 这意味着当我使用Chrome的REST客户端时,数据不会传递给API。

Am I missing something here? 我在这里错过了什么吗? Any help would be much appreciated. 任何帮助将非常感激。

UPDATE: 更新:

First, I json stringified the data variable: 首先,我json字符串化数据变量:

var data = JSON.stringify({
  'name': $scope.customerData.full_name,
});

and changed content type to application/x-www-form-urlencoded 并将内容类型更改为application/x-www-form-urlencoded

           addCustomer: function (data) {
                return $http({
                    method: 'POST',
                    url: '/api/customers',
                    data: data,
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
                });
            }

And in my php controller I tried: 在我的php控制器中我试过:

return $this->jsonResponse($this->request->post());

And I get this: 我得到了这个:

在此输入图像描述

Now I just have to access it. 现在我只需要访问它。 When I try $this->request->post('name') , I still get an error. 当我尝试$this->request->post('name') ,我仍然会收到错误。 So How can I properly get the json object? 那么我怎样才能正确获取json对象?

默认情况下$ http POST在json中发送数据,所以你需要在PHP中解析json字符串才能访问name属性,或者你可以将$ http params中的头文件更改为application / x-www-form-urlencoded如果你想在提交表格时获取参数。

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

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