Angular.JS HTTP POST数据未发送 [英] Angular.JS HTTP POST Data Not Sending

查看:123
本文介绍了Angular.JS HTTP POST数据未发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Angular.JS开发相当新,但过去曾经使用过PHP,HTML和JS,所以我目前正在构建一个Web应用程序,其中Angular.JS作为前端,PHP Slim作为API后端。我已成功使用Angular.JS $ http.post为我的一个调用实现基于令牌的身份验证,但似乎无法在另一个$ http.post请求中获得所需的结果,这不需要令牌身份验证。

I am fairly new to Angular.JS development but have had experience in the past with using PHP, HTML and JS so I am currently building a web application with Angular.JS as the frontend and PHP Slim as the API backend. I have been successful in implementing token-based authentication with Angular.JS $http.post for one of my calls but cannot seem to get the desired result in another $http.post request, which does not require the token authentication.

请求1 -
Angular.JS(工作):

REQUEST 1 - Angular.JS (WORKING):

  function ($scope, $http, $location) {
  console.log("REACHED");

  $scope.master = {};
  $scope.activePath = null;

  $scope.New_Customer = function(customer, AddNewForm) {
      console.log(customer);
      console.log("2: " + JSON.stringify(customer));

      console.log("SCOPE: " + customer.status);

      $http({
        method: "post",
        url: "v1/customers",
        headers: {
            'authorization': token,
            'Content-Type': 'application/x-www-form-urlencoded'
            },
        data: $.param({first_name: customer.first_name, last_name: customer.last_name, email: customer.email, mobile_number: customer.mobile_number, home_number: customer.home_number, address_line1: customer.address_line1, address_line2: customer.address_line2, city: customer.city, postalcode: customer.postalcode, 'status': customer.status})
        }).success(function(result){
          console.log(result);
          $scope.reset();
          $scope.activePath = $location.path('#/Customers');
        });

      $scope.reset = function() {
          $scope.customer = angular.copy($scope.master);
      };

      $scope.reset();
  };
}

PHP(工作)

$app->post('/customers', 'authenticate', function() use ($app) {
        // check for required params
        verifyRequiredParams(array('first_name'));

        $response = array();
        $first_name = $app->request->post('first_name');
        $last_name = $app->request->post('last_name');
        $email = $app->request->post('email');
        $mobile_number = $app->request->post('mobile_number');
        $home_number = $app->request->post('home_number');
        $address_line1 = $app->request->post('address_line1');
        $address_line2 = $app->request->post('address_line2');
        $city = $app->request->post('city');
        $postalcode = $app->request->post('postalcode');

        global $user_id;
        $db = new DbHandler();

        // creating new customer
        $customer_id = $db->createCustomer($user_id, $first_name, $last_name, $email, $mobile_number, $home_number, $address_line1, $address_line2, $city, $postalcode);

        if ($customer_id != NULL) {
            $response["error"] = false;
            $response["message"] = "Customer created successfully";
            $response["customer_id"] = $customer_id;
            echoRespnse(201, $response);
        } else {
            $response["error"] = true;
            $response["message"] = "Failed to create customer. Please try again";
            echoRespnse(200, $response);
        }            
    });

然而,对于我的登录脚本,数据似乎没有到达PHP文件所在的$ http.post请求始终在控制台中返回'null'。

However, for my login script, the data does not appear to be reaching the PHP file where the $http.post request always returns 'null' in the console.

请求2 - Angular.JS(不工作)

REQUEST 2 - Angular.JS (NOT WORKING)

  function ($scope, $http, $location) {
  console.log("REACHED");

  $scope.Login = function(customer, LoginForm) {
      console.log(customer);
      console.log("2: " + JSON.stringify(customer));

      console.log("SCOPE: " + customer.email);

  $http({
    url: "v1/login",
    method: "POST",
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    data: $.param({email: customer.email, password: customer.password})
}).success(function(data, status, headers, config) {
    $scope.data = data;
    console.log($scope.data);
}).error(function(data, status, headers, config) {
    $scope.status = status;
    $scope.data = data;
    console.log($scope.status + " " + $scope.data);
});  
  };
}

PHP(不工作)

$app->post('/login', function() use ($app) {

        // check for required params
        verifyRequiredParams(array('email', 'password'));

        $response = array();
        $email = $app->request()->post('email');
        $password = $app->request()->post('password');

        $db = new DbHandler();
        // check for correct email and password
        if ($db->checkLogin($email, $password)) {
            // get the user by email
            $user = $db->getUserByEmail($email);

            if ($user != NULL) {
                $response["error"] = false;
                $response['name'] = $user['name'];
                $response['email'] = $user['email'];
                $response['apiKey'] = $user['api_key'];
                $response['createdAt'] = $user['created_at'];
            } else {
                // unknown error occurred
                $response['error'] = true;
                $response['message'] = "An error occurred. Please try again";
            }
        } else {
            // user credentials are wrong
            $response['error'] = true;
            $response['message'] = 'Login failed. Incorrect credentials';
        }

        echoRespnse(200, $response);
    });

控制台日志:

app.js:148 REACHED
app.js:148 REACHED
/contacts_app_2/#/Login:1 POST http://localhost/contacts_app_2/ 412 (Precondition Failed)
Navigated to http://localhost/contacts_app_2/
app.js:148 REACHED
app.js:148 REACHED
app.js:151 Object {email: "test@test.com", password: "testpassword123"}
app.js:152 2: {"email":"test@test.com","password":"testpassword123"}
app.js:154 SCOPE: test@test.com
app.js:167 0 null
Navigated to http://localhost/contacts_app_2/
app.js:148 REACHED
app.js:148 REACHED

我似乎无法弄清楚为什么我的第一个请求(创建一个新客户)登录不起作用。任何有关这方面的帮助将不胜感激,因为我花时间浏览论坛以寻找其他答案但尚未找到解决此问题的方法。

I cannot seem to figure out why my first request (to create a new customer works) yet to login does not work. Any help with this would be greatly appreciated as I have spent time looking through the forums for other answers but have not yet found a way to resolve this issue.

推荐答案

通常,由于以下原因,AJAX请求失败:

Generally, AJAX requests are failed for these reason:


  1. 错误的网址或方法

  2. Cors request

  3. 阻止连接

由于您已经检查了 DevTools 并确保它不是第一个,并且您使用的是同一个域。让我们讨论第三个问题。

Since you have checked the DevTools and make sure it is not the first one, and you are using the same domain. Let discuss about the third one.

阻止连接可以通过 chrome:// net-internals /#events 。它出现的原因有断开网络防火墙问题。第二个有时很混乱,我猜你正面临着这个问题。我想你被你的插件阻止了,如 AdBlock

Blocked connection can be debugged by chrome://net-internals/#events. It happends for reasons like disconnected network, firewall issue. The second one is sometime very confusing, which I guess your are facing. I suppose you are blocked by your plugin like AdBlock.

这篇关于Angular.JS HTTP POST数据未发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆