Behnam Azimi
Behnam Azimi

Reputation: 2488

CORS work correctly on sharing host but not in localhost

I try to build a simple api base app with Laravel (as backend) and angularjs (as frontend). In the beginning, I faced this error:

XMLHttpRequest cannot load http://127.0.0.1:8000/api/myroute. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

That's while I've added the CORS middleware on my routes (according this sample) in this way: Cors Middleware:

public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
            ->header('Access-Control-Allow-Headers', 'x-requested-with, Content-Type, origin, authorization, accept, client-security-token');
    }

and the below code is my $http code that I send request in Angularjs:

$http({
    method: 'POST',
    url: 'http://127.0.0.1:8000/api/myroute',
    headers: {
        'Content-Type': 'application/json'
    }
}).then(function (response) {
    console.log(response);
}, function (reject) {
    console.log(reject);
});

I should to add this point that when I upload my project on a host, this Cors works Ok! My problem is just http://localhost.

I also tried this in Firefox but the result was same, just Firefox not shown the Cross Origin Error and it's the only difference.

In this time I could not develop my project on host and I need to work locally. So I need help!

Upvotes: 3

Views: 2423

Answers (1)

TohidNajafi
TohidNajafi

Reputation: 56

Try to add below codes as header to your laravel's index.php file:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization');

but be careful about cross origion!

Upvotes: 2

Related Questions