简体   繁体   中英

$_POST doesn't work well with $http POST

in my controller.js I do like this

$http({
        url: 'http://example.com/api.php',
        method: "POST",
        data: { 'YTParam' : 'test' }
    })
    .then(function(response) {
            console.log(response.data);
        }, 
        function(response) { // optional
            // failed
        }
    );

I even checked the network tool, the param did passed.

and in my api.php I try echo $_POST["YTParam"] but in my console I see nothing? What's wrong here? I tried to echo "string", it did appeared..

Angular未设置服务器处理的标头,请尝试使用此标头:

$_POST = json_decode(file_get_contents("php://input"), true);

Your data is not in the $_POST array, because your angular JS contentType is set to application/json by default, and PHP expects application/x-www-form-urlencoded for a POST request. Quoting from docs :

$httpProvider.defaults.headers.post: (header defaults for POST requests)

Content-Type: application/json

To change this, either change this value in your config :

yourApp.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";  
}]);

Or at the time you send your request :

$http({
    url: 'http://myURL.com/api/',
    method: "POST",

    headers: {
     'Content-Type': "application/x-www-form-urlencoded"
    },
    data: { 'YTParam' : 'test' }
})

You can set contentType directly as a property, but I'm not 100% sure of this.

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