Angularjs making post request to server. How to add key and value in angularjs using HTTP.POST. (ERROR : (POST http://IP/URL/ 403 (Forbidden)))

Angularjs making post request to server. How to add key and value in angularjs using HTTP.POST. (ERROR : (POST http://IP/URL/ 403 (Forbidden)))

我是 Angularjs 编程初学者,我想向我的服务器发出 post 请求。在服务器端,我正在等待带有键值对的数据。我想知道如何在 HTTP.post.

中添加键和值

附加信息: XAMP& 将 CodeIgniter 用于 API.


这就是我的控制器。

// calling our submit function.
    $scope.submitForm = function() {
    // Posting data to php file
        var data = ({
            'username': $scope.username,
            'password': $scope.password,
            'email': $scope.email,
            'fName': $scope.firstName,
            'lName': $scope.lastName,
            'gender': $scope.gender
        });

        var config = {
            headers : {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }

        $http.post('http://IP/URL/ ', data, config)
        .success(function (data, status, headers, config) {
            $scope.PostDataResponse = data;
        })
        .error(function (data, status, header, config) {
            $scope.ResponseDetails = "Data: " + data +
                "<hr />status: " + status +
                "<hr />headers: " + header +
                "<hr />config: " + config;
        });
    };

当我提交数据时,这就是我得到的。

控制台错误: http://i.stack.imgur.com/Qh8Ci.jpg

网络预览信息: "http://i.stack.imgur.com/oKtM4.jpg

我的问题的解决方案是

1) 将代码修改成这样

function ($scope, $http, $stateParams, $httpParamSerializerJQLike) {

$scope.data = {}
  // calling our submit function.
    $scope.submitForm = function() {
    // Posting data to php file


      $http({
    url: url,
    method: 'POST',
    data: $httpParamSerializerJQLike($scope.data),//
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
        'X-API-KEY' : '123456'
    }
  }) .success(function (data, status, headers, config) {
            $scope.PostDataResponse = data;
        })
        .error(function (data, status, header, config) {
            $scope.ResponseDetails = "Data: " + data +
                "<hr />status: " + status +
                "<hr />headers: " + header +
                "<hr />config: " + config;
        });
    };

我修改了上面的代码,感谢 Mike 提供给我的 link/post。 ( How do I POST urlencoded form data with $http in AngularJS? )

2) 我把 headers 改成这个

headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-API-KEY' : 'PASSWORD' })

3) 在 API(服务器端)

中将此实现到 rest_controller
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With,   
Content-Type, Accept, Access-Control-Request-Method");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
$method = $_SERVER['REQUEST_METHOD'];
if($method == "OPTIONS") {
die();
}