Reputation: 157
I followed this post but it only worked for GET method (as you can see it is mentioned in comments). I also installed this pakage but again it only works for GET method. This the error I get:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin my origin is therefore not allowed access. The response had HTTP status code 403.
PHP version: 7.1
Laravel version: 5.6
Frontend application: angular app (Do I need to change sth here?)
//Cours.php (middleware I created myself using the first method)
class Cors
{
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT,
DELETE, OPTIONS');
}
}
//cors.php (config/cors.php second method using the laravel-cors package)
return [
'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedOriginsPatterns' => [],
'allowedHeaders' => ['*'],
'allowedMethods' => ['*'],
'exposedHeaders' => [],
'maxAge' => 0,
];
//kernel.php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
\Barryvdh\Cors\HandleCors::class,
];
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'cors' => \App\Http\Middleware\Cors::class,
];
}
Upvotes: 0
Views: 11363
Reputation: 1
I also encountered this error while trying to create an endpoint for a serial number checker on wordpress using laravel So just use the cors generated by laravel
<?php
namespace App\Http\Middleware;
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);
$response->headers->set('Access-Control-Allow-Origin' , '*');
$response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
$response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');
return $response;
}
}```
Then exclude the route if you are it does not need CSRF protection [as shown here][1] . The cors.php under config remains the same just adjust the `allowed origins`
```php
<?php
return [
/*
|--------------------------------------------------------------------------
| Allowed Origins
|--------------------------------------------------------------------------
|
| Indicate here the origin domains that are allowed to access your API.
| The '*' wildcard can be used to allow all domains to make requests.
|
*/
'allowed_origins' => [
'http://localhost',
'http://localhost/wordpresss',
],
/*
|--------------------------------------------------------------------------
| Allowed HTTP Headers
|--------------------------------------------------------------------------
|
| Indicate here the HTTP headers that are allowed when making requests.
|
*/
'allowed_headers' =>['*'],
/*
|--------------------------------------------------------------------------
| Allowed HTTP Methods
|--------------------------------------------------------------------------
|
| Indicate here the HTTP methods that are allowed when making requests.
|
*/
'allowed_methods' => ['*'],
/*
|--------------------------------------------------------------------------
| Whether or not the response can be exposed when credentials are present
|--------------------------------------------------------------------------
|
| Indicates whether or not the response to the request can be exposed when the credentials flag is true.
| When used as part of a response to a preflight request, this indicates whether or not the actual request
| can be made using credentials.
|
*/
'exposed_headers' => [],
/*
|--------------------------------------------------------------------------
| Whether or not the request can include user credentials like cookies, HTTP authentication or client side SSL certificates
|--------------------------------------------------------------------------
|
| Indicates whether or not the response to the request can be exposed when the credentials flag is true.
| When used as part of a response to a preflight request, this indicates whether or not the actual request
| can be made using credentials.
|
*/
'allow_credentials' => false,
/*
|--------------------------------------------------------------------------
| The number of seconds the client should cache preflight responses
|--------------------------------------------------------------------------
|
| Indicates how long the results of a preflight request can be cached in a preflight result cache.
|
*/
'max_age' => 0,
];
Happy coding glad I could save someone some time!!!
Upvotes: 0
Reputation: 21
No need any type package for laravel-cors. Just create Middleware:
namespace App\Http\Middleware;
use Closure;
class Cors {
public function handle($request, Closure $next) {
$allowedOrigins = ['http://myroute.xyz', 'http://clarkconcepts.net','http://localhost'];
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
if (in_array($origin, $allowedOrigins)) {
return $next($request)
->header('Access-Control-Allow-Origin', $origin)
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers',' Origin, Content-Type, Accept, Authorization, X-Request-With, cache-control,postman-token, token')
->header('Access-Control-Allow-Credentials',' true');
}
return $next($request);
}
}
In app/Http/Kernel.php add Middleware in $middleware section:
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\Cors::class, //added here
];
Upvotes: 2
Reputation: 11
you need use first method this post without use any package then add also this class to protected $middleware
like this post then post method also have desired headers.
it works for me, I hope work for you.
Upvotes: 1
Reputation: 47
You could also use the great laravel-cors package by barryvdh.
After you have the package installed, the easiest way to get CORS support for all your routes is to add the middleware like this in Http/Kernel.php: ($middleware)
\Barryvdh\Cors\HandleCors::class
And edit config/Cors.php
'allowedOrigins' => ['*']
More info check https://github.com/barryvdh/laravel-cors/blob/master/readme.md
Upvotes: 0