Laravel 5.2 Cors, Get Not Working with Preflight Options

Laravel 5.2 CORS, GET not working with preflight OPTIONS

Clearly not the ideal solution but it WORKS. I've added this to the top of my routes.php file:

header('Access-Control-Allow-Origin: *');
header( 'Access-Control-Allow-Headers: Authorization, Content-Type' );

It would be nice to get this working without a hack... alas.

UPDATE: It turned out to be IIS related. I ended up setting the headers in the web.config file and now CORS works without hacking the routes.php file.

<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Headers" value="Origin, Authorization, X-Requested-With, Content-Type, Accept" />
<add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS,PUT,DELETE" />
</customHeaders>
</httpProtocol>

If you want to restrict access, you can add outbound rules:

      <outboundRules>
<clear />
<rule name="AddCrossDomainHeader">
<match serverVariable="RESPONSE_Access_Control_Allow_Origin" pattern=".*" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="true">
<add input="{HTTP_ORIGIN}" pattern="(http(s)?://((.+\.)?somesite\.com|(.+\.)?anothersite\.org))" />
</conditions>
<action type="Rewrite" value="{C:0}" />
</rule>
</outboundRules>

Laravel 9 - CORS is not working (Access to XMLHttpRequest has been blocked by CORS policy)

I find a solution for my problem, I was trying to fetch data from http://localhost:8000/api and when I checked cors.php file I find the paths key contains 2 values like the following:

'paths' => ['api/*', 'sanctum/csrf-cookie']

so like I said I was navigating to api path not api/* only so the array should contain a value of the 'api' like the following:

'paths' => ['api/*', 'sanctum/csrf-cookie', 'api']

How to Solve CORS error in accessing laravel routes

I had the same problem, solved it by Middleware

Define your custom middleware

//App\Http\Middleware;

public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', '*')
->header('Access-Control-Allow-Credentials', true)
->header('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type,X-Token-Auth,Authorization')
->header('Accept', 'application/json');
}

Than just register yours Middleware, local (for specific route/routes) or global.

How to register Middleware

Notice! Some old brovsers do not support '*' logic



Related Topics



Leave a reply



Submit