'Laravel 5.5 CORS issue when loading FontAwesome 4.7.0
I get a problem. I already read a lot of reference but still get error.
Access to font at 'http://192.168.0.1/fonts/fontawesome-webfont.woff2?v=4.7.0' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
What i have done?
First Effort
I try to make new file .htaccess in /public/font folder.
Inside .htaccess i write :
<FilesMatch "\.(ttf|otf|eot|woff|woff2)$">
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
</FilesMatch>
Second effort
I try to use Middleware, create new file call CORS.php
Inside CORS.php i write
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode as Middleware;
use Closure;
use Illuminate\Support\Facades\Response;
use Log;
class CORS extends Middleware {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
Log::info("CORS 1");
$origin = $request->header('origin');
Log::info("Origin in CORS : $origin");
$origin = $origin ?? '*';
// ALLOW OPTIONS METHOD
// $headers = [
// 'Access-Control-Allow-Origin' => $origin,
// 'Access-Control-Allow-Methods'=> 'GET, POST, DELETE, PUT, OPTIONS, HEAD, PATCH',
// 'Access-Control-Allow-Headers'=> 'Authorization,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Set-Cookie',
// 'Access-Control-Allow-Credentials'=> 'true'
// ];
$headers = [
'Access-Control-Allow-Origin' => $origin,
'Access-Control-Allow-Methods'=> 'GET, POST',
'Access-Control-Allow-Headers'=> 'Authorization,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Set-Cookie',
'Access-Control-Allow-Credentials'=> 'true'
];
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);
}
Log::info("CORS");
Log::info($response);
return $response;
}
}
Result :
First effort and Second Effort still not works. Second effort only works for API request (if you add GET and OPTIONS in API).
My Question :
My goal is i want to access fontawesome from other Laravel Server. What's my fault?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
