I built an API on Laravel5 and had CORS issues on localhost in development enviroment, so I developed this middleware and used on the API's routes, which solved the issue:
<?php
namespace App\Http\Middleware;
use Illuminate\Support\Facades\Log;
use Closure;
class Cors
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request)
->header('Access-Control-Allow-Origin', 'http://zekrishna.com')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
return $response;
}
}
When I depolyed the app the CORS problems started again. I used the same server to host the API and front-end, where the front-end is on the server's root and the API on a subdomain.
Here's my .htacess on public/
:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>
<IfModule mod_headers.c>
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
</IfModule>
What am I doing wrong?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire