Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
139
rated 0 times [  145] [ 6]  / answers: 1 / hits: 7409  / 11 Years ago, tue, february 4, 2014, 12:00:00

I have been searching far and wide for a solution to this problem.



I have an AngularJS web app with a Laravel 4 backend implementation as follows:



http://app.mydomain.io/ = AngularJS web app
http://api.mydomain.io/ = Laravel Back-end


Within the routes.php file in Laravel I have the following PHP code to set the Access-Control headers:



header('Access-Control-Allow-Origin: http://app.mydomain.io');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');


I also have a route set-up for a login request as follows:



Route::post('/login', function()
{
$email = Input::get('email');
$password = Input::get('password');
if (Auth::attempt(array('email' => $email, 'password' => $password)))
{
return Success!;
} else {
return Fail!;
}
});


In AngularJS I have a AuthService which looks like below:



app.factory('AuthService', ['$resource', '$q', '$cookieStore', function($resource, $q, $cookieStore) {
var user = null;
var Service = $resource('//api.mydomain.io/login/', {}, {});
return {
login: function(email, password) {
var deferred = $q.defer();
Service.save({email: email, password: password}, function(response) {
$cookieStore.put('user', JSON.stringify(response));
deferred.resolve(true);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
};
}]);


When this request is made I get the following:



XMLHttpRequest cannot load http://api.mydomain.io/login. Invalid HTTP status code 404


If I change the Laravel route and AngularJS service to use GET, everything works as expected. The problem stems from AngularJS .save() making a OPTIONS request instead of POST (I don't fully understand why).



Could anyone help me with the proper and best practice solution?



Thank you!


More From » php

 Answers
3

The following solution worked:



Within filters.php add the following:



App::before(function($request)
{
if (Request::getMethod() == OPTIONS) {
$headers = array(
'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers'=> 'X-Requested-With, content-type',);
return Response::make('', 200, $headers);
}
});


And at the top of routes.php add the following:



header('Access-Control-Allow-Origin: http://app.mydomain.io');


Thanks to the Google Plus community! :)



Leon.


[#48066] Tuesday, February 4, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaredsages

Total Points: 273
Total Questions: 97
Total Answers: 105

Location: French Southern and Antarctic Lands
Member since Fri, Jan 6, 2023
1 Year ago
jaredsages questions
;