简体   繁体   中英

AngularJS can't sent POST request to SLIM Framework

Hello I have this angularjs http.post() request to slim php framework.

  'use strict';

   soup.factory('loginService',function($http){
    return {
        login:function(user){
                         console.log(user);

            var $promise = $http.post('api/vendor/slim/slim',user );
            return $promise;
    };
});

when I debug the $_POST it always return an empty array,

but when I use use json_decode(file_get_contents('php://input')) , slim php will return an error.

this is php function that handle the request.

function login(){
    $sql = "SELECT * FROM users ORDER by id";
     try {
        $db = getConnection();
        $stmt = $db->query($sql);
        $users = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
        //print_r($users);
        $users = json_encode($users);


    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }

    var_dump($_POST);
    $test = json_decode(file_get_contents('php://input'));

    //do something with the post data



}

how can I solve this?

$http api say:

params – {Object.} – Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified.

Try sending data as a string, something like this:

var $promise = $http({
    url: 'api/vendor/slim/slim',                                                method: 'POST',
    data: 'user=' + usr + '&password=' + pwd,
    headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
});

Don't forget to include the Content-Type header.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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