Gowtham A Satheesh
Gowtham A Satheesh

Reputation: 13

Access to XMLHttpRequest at 'production_api_url' from origin 'localhost' has been blocked by CORS policy

I am working on a project which build a website by using Angular 2 as frontend and Laravel 5.7. In the website, I am trying to implement a user profile section like, login, signup, password reset, forgot password, profile view, edit profile. I am written all the apis needed for the user profile section and tested it in the POSTMAN and everything become fine. But, when I am trying to implement the apis which needs the api token, there I got this error

Access to XMLHttpRequest at 'http://www.peterbookhouse.com/vibes/backend/public/api/changePassword' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status."

I can't find a solution for this. Please help me to find a solution for this issue.

Thanks in advance

I already created middleware for CORS and added that middleware for the routes which needs.

I tried two different codes in the middleware. I here pasting those codes.

1.

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, X-Token-Auth, Authorization’);

2.

header("Access-Control-Allow-Origin: *");

    // ALLOW OPTIONS METHOD
    $headers = [
        'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
        'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin, Authorization'
    ];


if($request->getMethod() == "OPTIONS") {
    // The client-side application can set only headers allowed in Access-Control-Allow-Headers
    return Response::make('OK', 200, $headers);
}

$response = $next($request);
foreach($headers as $key => $value)
    $response->header($key, $value);
return $response;

Upvotes: 0

Views: 8992

Answers (1)

RAJEESH PM
RAJEESH PM

Reputation: 83

Try adding these headers in top of your laravel applications routes/api.php

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");

Upvotes: 1

Related Questions