简体   繁体   English

来自 angular 的 $http.post 到达 php,但在 angularjs 中未收到响应

[英]$http.post from angular reaches php, but response is not received back in angularjs

I'm having this weird issue where you already did something thousands of time but this time won't work.我遇到了一个奇怪的问题,您已经做了数千次但这次不起作用。 I've been on it for two days and can't fix it.我已经用了两天了,无法修复它。

So my code is very simple :所以我的代码很简单:

js : js:

$http.post('datas/test.php', data)
    .success(function(response) 
             console.log(response);
     })
    .error(function() {
             console.log("error");
     });

test.php :测试.php:

<?php
$user=json_decode(file_get_contents('php://input'));
echo json_encode($user);
?>

When I do a console.log(data) before the $http.post it's containing an object with two fields which are both strings but the console.log(response) give me a null so every time I try to access a variable like $user->something it gives me an error.当我在 $http.post 之前执行 console.log(data) 时,它包含一个具有两个字段的对象,这两个字段都是字符串,但是 console.log(response) 给我一个 null 所以每次我尝试访问像 $ 这样的变量时用户-> 它给了我一个错误。

I'm having a second issue that is really weird too : when I run my app and call the $http.post it gives me all the errors I said before, but if I try an other time, the $http.post won't call at all until I reboot the server (it's giving me a bad gateway).我还有一个很奇怪的问题:当我运行我的应用程序并调用 $http.post 时,它给了我我之前说过的所有错误,但是如果我再试一次,$http.post 将不会出现在我重新启动服务器之前根本不调用(它给了我一个坏网关)。

I tested many things like changing the way I call my file :我测试了很多东西,比如改变我调用文件的方式:

$http({
    method: 'POST',
    url: 'datas/test.php',
    data: data,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'} // Or 'application/json'
});

but this is giving me exactly the same behavior.但这给了我完全相同的行为。

Thank you in advance for helping me out and have a good day !预先感谢您帮助我,祝您有美好的一天! ;) ;)

PS: I'm using PHPStorm in case it has anything to do with the server reboot thing. PS:我正在使用 PHPStorm,以防它与服务器重启有关。

If you use the content type 'application/x-www-form-urlencoded' you should pass the data in the urlencoded format (ie. "var1=val1&var2=val2").如果您使用内容类型“application/x-www-form-urlencoded”,您应该以 urlencoded 格式(即“var1=val1&var2=val2”)传递数据。

Otherwise, if you use 'application/json', you can pass directly your javascript object.否则,如果您使用“application/json”,您可以直接传递您的 javascript 对象。

Let me know if I can help you better.如果我能更好地帮助你,请告诉我。

Bye再见

For First Approach对于第一种方法

To use angular $http.post in correct way you shoud handal promise correctly by using .then method not the success method.要以正确的方式使用 angular $http.post,您应该使用 .then 方法而不是成功方法正确处理 promise。

$http.post('/someUrl', data, config).then(successCallback, errorCallback);

Please check the angular documentation for using $http.post请检查角度文档以使用 $http.post

For Second Approach对于第二种方法

Look like data is not transform correctly.看起来数据没有正确转换。 By default, the $http service will transform the outgoing request by serializing the data as JSON and then posting it with the content-type, "application/json".默认情况下,$http 服务将通过将数据序列化为 JSON,然后使用内容类型“application/json”发布它来转换传出请求。 But you want to post the value as a FORM post, so you need to change the serialization algorithm and post the data with the content-type, "application/x-www-form-urlencoded".但是您想将值作为 FORM 帖子发布,因此您需要更改序列化算法并使用内容类型“application/x-www-form-urlencoded”发布数据。

Following code reference from this link以下来自此链接的代码参考

var request = $http({
method: "post",
url: "datas/test.php",
transformRequest: transformRequestAsFormPost,
data: {
  id: 4,
  name: "Test",
  status: "Something"
}
});

// Store the data-dump of the FORM scope.
request.success(
function( html ) {

$scope.cfdump = html;

}
);

And the TransformRequestAsFormPost implementation和 TransformRequestAsFormPost 实现

app.factory(
"transformRequestAsFormPost",
function() {

// I prepare the request data for the form post.
function transformRequest( data, getHeaders ) {

var headers = getHeaders();

headers[ "Content-type" ] = "application/x-www-form-urlencoded; charset=utf-8";

return( serializeData( data ) );

}


// Return the factory value.
return( transformRequest );


// ---
// PRVIATE METHODS.
// ---


// I serialize the given Object into a key-value pair string. This
// method expects an object and will default to the toString() method.
// --
// NOTE: This is an atered version of the jQuery.param() method which
// will serialize a data collection for Form posting.
// --
// https://github.com/jquery/jquery/blob/master/src/serialize.js#L45
function serializeData( data ) {

// If this is not an object, defer to native stringification.
if ( ! angular.isObject( data ) ) {

return( ( data == null ) ? "" : data.toString() );

}

var buffer = [];

// Serialize each key in the object.
for ( var name in data ) {

if ( ! data.hasOwnProperty( name ) ) {

continue;

}

var value = data[ name ];

buffer.push(
encodeURIComponent( name ) +
"=" +
encodeURIComponent( ( value == null ) ? "" : value )
);

}

// Serialize the buffer and clean it up for transportation.
var source = buffer
.join( "&" )
.replace( /%20/g, "+" )
;

return( source );

}

}
);

The problem I had here came from a FileReader I opened earlier in my JS :我在这里遇到的问题来自我之前在 JS 中打开的 FileReader:

reader.readAsBinaryString($scope.file);
    reader.onload = function (e) {
       //stuff
    };

the readAsBinaryString function made the file_get_contents("php://input") unable to work correctly. readAsBinaryString 函数使 file_get_contents("php://input") 无法正常工作。

Once replaced with一旦被替换为

    reader.readAsDataURL($scope.file);

every thing worked fine.一切正常。

Thanks to Giulio for helping me to troubleshoot this.感谢 Giulio 帮助我解决这个问题。

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

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