Programador Adagal Programador Adagal - 3 months ago 69
AngularJS Question

Laravel 5.2 API Rest and Angular JS - $HTTP_RAW_POST_DATA is deprecated

I am trying to send an $http.post AJAX data to a route configured in Laravel 5.2, everything works perfect, but the server returns this error:


Deprecated: Automatically populating $HTTP_RAW_POST_DATA is deprecated
and will be removed in a future version. To avoid this warning set
'always_populate_raw_post_data' to '-1' in php.ini and use the
php://input stream instead. in Unknown on line 0

Warning: Cannot modify header information - headers already sent in
Unknown on line 0


This is my code. PHP:

public function save(Request $request){
$input = $request->all();
try {
$direccion = urlencode($input['Calle']." ".$input['Numero'].", ".$input['Ciudad']);

$geocode = "https://maps.googleapis.com/maps/api/geocode/json?address=$direccion&key=APIKEY";
$datosGoogle = json_decode($this->curl($geocode), true);

$latitud = $datosGoogle['results'][0]['geometry']['location']['lat'];
$longitud = $datosGoogle['results'][0]['geometry']['location']['lng'];

if(is_double($latitud) && is_double($latitud)){
$input['Latitud'] = $latitud;
$input['Longitud'] = $longitud;
$new = MyModel::create($input);
$data = ["status"=>"ok", "message"=>"Agregado correctamente"];
}else{
$data = ["status"=>"fail", "message"=>"Dirección desconocida, compruebe que los datos son correctos para que podamos agregarla al sistema."];
}
} catch (Exception $e) {
$data = ["status"=>"error", "message"=>$e->getMessage()];
}
return response()->JSON($data);
}


JS:

$scope.registrar = function(form, datos) {
$scope.submitted = true;
if(form.$valid) {
var toSendData = JSON.stringify({
Nombre: datos.nombre,
Calle: datos.calle,
Numero: datos.numero,
Piso: datos.piso,
Puerta: datos.puerta,
CP: datos.cp,
Ciudad: datos.ciudad,
Email: datos.email,
Necesidades: datos.necesidades,
Telefono: datos.telefono
});
console.log(toSendData);
$http.post($rootScope.recibirNuevoUrl, toSendData).then(function(response){
$scope.hideLoading();
if(response.data.status == "ok"){
$state.go('registro');
}else{
$scope.$parent.showAlert("Error al introducir los datos", response.data.message);
}
})
}else{
$scope.$parent.showAlert('Validacion de datos', 'El formulario contiene errores. Por favor revise los campos marcados para comprobar los errores.');
}
};


How can I fix it?

Answer

I had the same problem with Laravel 5.2 and Angular, I got it working by adding a single line in my controller:

editorApp.controller('EditorCtrl', function ($scope, $sce, $http, $location, $interval, $document){

    $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

    ...

I found this working for me in this post: http://stackoverflow.com/a/19254137/4021927. The answer marked as correct did not work for me, the line above is from an other answer in the same post. The correct answer (http://stackoverflow.com/a/20276775/4021927) does tell you why you need it though.

In short why this problem exist is because Angular (By default) send data using JSON serialization: Content-Type: application/json and PHP does not unserialize JSON natively. By changing content-type to x-www-form-urlencoded the data will be sent as:

foo=bar&bar=foo

instead of (JSON):

{ "foo": "bar", "bar": "foo" }