fruitcake / laravel-cors

Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application
MIT License
6.27k stars 614 forks source link

No 'Access-Control-Allow-Origin' #421

Closed baftijarovskiA closed 4 years ago

baftijarovskiA commented 4 years ago

I write everything as stated in the readme.md file but still get an error on my requests. No 'Access-Control-Allow-Origin' header is present on the requested resource. I am using Laravel 6

felixivance commented 4 years ago

Experiencing the same problem, what might be the issue

jekabsmilbrets commented 4 years ago

Same here

orijmm commented 4 years ago

Same

jm21 commented 4 years ago

GET requests seem to be working fine, POST requests are not going through in my case

barryvdh commented 4 years ago

What is your config?

jm21 commented 4 years ago
return [

    /*
    |--------------------------------------------------------------------------
    | Laravel CORS Options
    |--------------------------------------------------------------------------
    |
    | The allowed_methods and allowed_headers options are case-insensitive.
    |
    | You don't need to provide both allowed_origins and allowed_origins_patterns.
    | If one of the strings passed matches, it is considered a valid origin.
    |
    | If array('*') is provided to allowed_methods, allowed_origins or allowed_headers
    | all methods / origins / headers are allowed.
    |
    */

    /*
     * You can enable CORS for 1 or multiple paths.
     * Example: ['api/*']
     */
    'paths' => ['api/*'],

    /*
    * Matches the request method. `[*]` allows all methods.
    */
    'allowed_methods' => ['*'],

    /*
     * Matches the request origin. `[*]` allows all origins.
     */
    'allowed_origins' => ['*'],

    /*
     * Matches the request origin with, similar to `Request::is()`
     */
    'allowed_origins_patterns' => ['*'],

    /*
     * Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers.
     */
    'allowed_headers' => ['*'],

    /*
     * Sets the Access-Control-Expose-Headers response header.
     */
    'exposed_headers' => false,

    /*
     * Sets the Access-Control-Max-Age response header.
     */
    'max_age' => false,

    /*
     * Sets the Access-Control-Allow-Credentials header.
     */
    'supports_credentials' => false,
];
barryvdh commented 4 years ago

Did you clear the config cache? What is the actual path you post to?

jm21 commented 4 years ago

I've cleared config cache. Posting to http://localhost/capslock-admin/backend/public/api/login

barryvdh commented 4 years ago

That's an unusual path, perhaps try or `api*`

jm21 commented 4 years ago

If I set paths to 'paths' => ['*'] GET requests work. POST requests are not working at all

barryvdh commented 4 years ago

And you added the middleware to the global middleware? Not just the group?

George-Krause commented 4 years ago

same problem here, I did add the HandleCors to the globale middlewares...set config to '*' on neccessary fields...

Image: https://pasteboard.co/IVrYSyx.png

jm21 commented 4 years ago

I added the middleware, didn't work. Removed it, still didn't work

barryvdh commented 4 years ago

Cam you add some logging to https://github.com/fruitcake/laravel-cors/blob/master/src/HandleCors.php ? Maybe check if shouldRun or isMatchingPath are returning true correctly.

George-Krause commented 4 years ago

I found my issue: I had to sent "Accept: application/json" HTTP-Header to laravel...without "accept"-header it does not work.

phuchnh commented 4 years ago

Maybe you should check \Fruitcake\Cors\HandleCors::class already added in $middleware of app/Http/Kernel.php or not?

shadowgroundz commented 4 years ago

+1 I have some issue to. No problem with get request

suppergohan commented 4 years ago

I had to sent "Accept: application/json" HTTP-Header to laravel. Not working.

shadowgroundz commented 4 years ago

In my case, it happen if I read base64 data from $request. But if I not read there is no problem

barryvdh commented 4 years ago

Are you not having errors (eg. CSRF errors?) Can you put some loggers? Is the same request working with Postman? Can you show how you output/create the response?

shadowgroundz commented 4 years ago

Are you not having errors (eg. CSRF errors?) Can you put some loggers? Is the same request working with Postman? Can you show how you output/create the response?

Hi, thanks for your response. This my config

<?php
return [
    'paths' => ['api/*'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => false,
    'max_age' => false,
    'supports_credentials' => true,
];

When I hit use my ReactJs app respose is like this

Screen Shot 2020-02-24 at 15 33 19

But when I hit using postman result show what I want

Screen Shot 2020-02-24 at 15 36 58
barryvdh commented 4 years ago

Are all of you using some sub-path? eg. localhost/yourproject/public/api.. ?

shadowgroundz commented 4 years ago

I use /public/ just only for development

nalletje commented 4 years ago

Are you not having errors (eg. CSRF errors?) Can you put some loggers? Is the same request working with Postman? Can you show how you output/create the response?

Hi, thanks for your response. This my config

<?php
return [
    'paths' => ['api/*'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => false,
    'max_age' => false,
    'supports_credentials' => true,
];

When I hit use my ReactJs app respose is like this

Screen Shot 2020-02-24 at 15 33 19

But when I hit using postman result show what I want

Screen Shot 2020-02-24 at 15 36 58

Are you sure the ReactJS is not sending a OPTIONS request before the POST request? Every time struggling with that again with NuxtJS.

Mostly the server configuration needs to change to allow method request OPTIONS to fix this for me.

shadowgroundz commented 4 years ago

Are you not having errors (eg. CSRF errors?) Can you put some loggers? Is the same request working with Postman? Can you show how you output/create the response?

Hi, thanks for your response. This my config

<?php
return [
    'paths' => ['api/*'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => false,
    'max_age' => false,
    'supports_credentials' => true,
];

When I hit use my ReactJs app respose is like this

Screen Shot 2020-02-24 at 15 33 19

But when I hit using postman result show what I want

Screen Shot 2020-02-24 at 15 36 58

Are you sure the ReactJS is not sending a OPTIONS request before the POST request? Every time struggling with that again with NuxtJS.

Mostly the server configuration needs to change to allow method request OPTIONS to fix this for me.

Yes sure. Not send option before hit any api. But not problem for any GET request

miharbi commented 4 years ago

Same error here

barryvdh commented 4 years ago

Does it happen with php artisan:serve? Did you clear the cache (config etc) and check the permissions for the storage/bootstrap folders?

sinceow commented 4 years ago

I faced the same problem, and tried everything mentioned above, still not working

nalletje commented 4 years ago

Did you guys consider trying returning JSON (or checking if it returns JSON)? In the postman screenshot i see he's returning an array instead of JSON.

jeherrera commented 4 years ago

I had this same issue and it seems to have been resolved by adding HandleCors::class to the top of the $middlewarePriority list in addition to the $middleware list as noted in the docs:

protected $middlewarePriority = [
        \Fruitcake\Cors\HandleCors::class, //<- this seems to have been the missing piece for me
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\Authenticate::class,
        \Illuminate\Routing\Middleware\ThrottleRequests::class,
        \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \Illuminate\Auth\Middleware\Authorize::class,
    ];
p2sousa commented 4 years ago

I had the same problem, but I was registering the middleware only in the api group, it was resolved by registering it in the global middleware.

\App\Http\Kernel.php

protected $middleware = [
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \Fruitcake\Cors\HandleCors::class,
];

in config/cors.php I had to specify the path.

config/cors.php

$origins = env('CORS_ORIGINS', []);
return [
    'paths' => ['api/*'],
    'allowed_methods' => ['*'],
    'allowed_origins' => explode(',', $origins),
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => false,
    'max_age' => false,
    'supports_credentials' => false,
];
commeco commented 4 years ago

I had this same issue and it seems to have been resolved by adding HandleCors::class to the top of the $middlewarePriority list in addition to the $middleware list as noted in the docs:

protected $middlewarePriority = [
        \Fruitcake\Cors\HandleCors::class, //<- this seems to have been the missing piece for me
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\Authenticate::class,
        \Illuminate\Routing\Middleware\ThrottleRequests::class,
        \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \Illuminate\Auth\Middleware\Authorize::class,
    ];

Hi, in our case the sort order in the $middleware array was the solution.

protected $middleware = [
        \Fruitcake\Cors\HandleCors::class,         <-- It must be the first entry here!
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];
barryvdh commented 4 years ago

Can you check which middleware makes the difference?

commeco commented 4 years ago

Can you check which middleware makes the difference?

Sorry Barry. It was a false alarm. The problem was the php opcache. :-/ It works in any sort order.

Regards Matthias

ahmedkhan847 commented 4 years ago

@barryvdh I am facing the same issue with the CORS tried everything its not working

this is my middleware

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Fruitcake\Cors\HandleCors::class,
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,

    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    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',
            \Fruitcake\Cors\HandleCors::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    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,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'json.response' => \App\Http\Middleware\ForceJsonResponse::class
    ];

    /**
     * The priority-sorted list of middleware.
     *
     * This forces non-global middleware to always be in the given order.
     *
     * @var array
     */
    protected $middlewarePriority = [
        \Fruitcake\Cors\HandleCors::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\Authenticate::class,
        \Illuminate\Routing\Middleware\ThrottleRequests::class,
        \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \Illuminate\Auth\Middleware\Authorize::class,
    ];
}

this is my config

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Laravel CORS Options
    |--------------------------------------------------------------------------
    |
    | The allowed_methods and allowed_headers options are case-insensitive.
    |
    | You don't need to provide both allowed_origins and allowed_origins_patterns.
    | If one of the strings passed matches, it is considered a valid origin.
    |
    | If array('*') is provided to allowed_methods, allowed_origins or allowed_headers
    | all methods / origins / headers are allowed.
    |
    */

    /*
     * You can enable CORS for 1 or multiple paths.
     * Example: ['api/*']
     */
    'paths' => ['api/*'],

    /*
    * Matches the request method. `[*]` allows all methods.
    */
    'allowed_methods' => ['*'],

    /*
     * Matches the request origin. `[*]` allows all origins.
     */
    'allowed_origins' => ['*'],

    /*
     * Matches the request origin with, similar to `Request::is()`
     */
    'allowed_origins_patterns' => [],

    /*
     * Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers.
     */
    'allowed_headers' => ['*'],

    /*
     * Sets the Access-Control-Expose-Headers response header.
     */
    'exposed_headers' => false,

    /*
     * Sets the Access-Control-Max-Age response header.
     */
    'max_age' => false,

    /*
     * Sets the Access-Control-Allow-Credentials header.
     */
    'supports_credentials' => false,
];
alexanderbenerink commented 4 years ago

@barryvdh I am facing the same issue with the CORS tried everything its not working

Me too. I can't wrap my head around where the problem originates from. I created a clean laravel 6 installation, merged our old projects files into it, fixed the bugs and added this package but to no avail. Locally it works, mind you. It also works when I send my headers to a script in JSFiddle, edit: from localhost**. My api is then visible and working.

But when it's on production/server the websites connected to our api still get this error. I changed permissions for storage, cleared all the caches/config, I use fruitcake/laravel-cors: "^1.0", my laravel version is 6.18.0, my dev server php version is 7.4 and my project is php version 7.2.9.

If I add this in or outside the "IfModule mod_headers.c" tag in my .htaccess file:

Header always set Access-Control-Allow-Origin " " Header always set Access-Control-Allow-Methods: " ":

It changes the error from this:

"Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

to this:

"Response to preflight request doesn't pass access control check: It does not have HTTP ok status.""

I feel like I'm close, however that still won't get me anywhere. The HandleCors class is inside the global $middleware, inside the Cors config file I use a wildcard for allowed_origins, allowed_methods and allowed_headers. Changing the path won't have any effect but it is "api/*".

Would it possibly have something to do with my api routes file?

routes > api.php:

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

//Route::group(['config' => 'cors'], function () {
    Route::options('{any}'); // CORS Preflight

    Route::get('/app/{application}/layout', 'Api\LayoutController@index');
    Route::get('/app/{application}', 'Api\PageController@index');
    Route::get('/app/{application}/{page_id}', 'Api\PageController@show');
    Route::post('/app/{application}/search', 'Api\SearchController@index');
    Route::post('/app/{application}/review', 'Api\ReviewController@index');
    Route::post('/app/{application}/review-comment', 'Api\ReviewController@comment');
    Route::post('/app/{application}/form', 'Api\FormController@index');
    Route::post('/app/{application}/message', 'Api\MessageController@store');
    Route::post('/app/{application}/chat', 'Api\MessageController@index');
//});

Or has it something to do with the server? And adding the mod_headers.c to my httpd.conf on the server won't give me any results either. I've been at this for a week now.

barryvdh commented 4 years ago

You don;t have to define the Route::options and not sure what the config => cors is?

alexanderbenerink commented 4 years ago

You don;t have to define the Route::options and not sure what the config => cors is?

Originally we had a custom middleware but it didn't work anymore so we switched to the package. I uncommented it but I should've removed it for clarity in my previous post. sorry

barryvdh commented 4 years ago

But what is Route::options('{any}');?

alexanderbenerink commented 4 years ago

But what is Route::options('{any}');?

To allow preflighting for every route/slug/whathaveyou. I ported the project from 5.4 to 6. That might have something to do with it? I doubt it

icebay commented 4 years ago

In my case, set supports_credentials to true, it works

icebay commented 4 years ago

In my case, set supports_credentials to true, it works

Because i set credentials in React.js

Bluefitdev commented 4 years ago

It doesn't seem to work on mine either.

Sorted the middleware class, put everything on * in config file, nothing seems to work....

I'm using default one from laravel 7

Bluefitdev commented 4 years ago

Mine is having an error on the addActualHeaderRequest

It still returns my Origin is not allowed by Access-Control-Allow-Origin even though in config its setup to *

    public function handle($request, Closure $next)
    {
        // Check if we're dealing with CORS and if we should handle it
        if (!$this->shouldRun($request)) {
            Log::info('Goes in should run');

            return $next($request);
        }

        // For Preflight, return the Preflight response
        if ($this->cors->isPreflightRequest($request)) {
            return $this->cors->handlePreflightRequest($request);
        }

        // If the request is not allowed, return 403
        if (!$this->cors->isActualRequestAllowed($request)) {
            Log::info('Goes in not allowed');

            return new Response('Not allowed in CORS policy.', 403);
        }

        // Handle the request
        $response = $next($request);
        Log::info('Handled is: '.$response);

        // Add the CORS headers to the Response
        return $this->addHeaders($request, $response);
    }

I got the response in the handle correctly But it doesn't go through the return

[2020-03-11 01:12:38] local.INFO: Handled is: HTTP/1.1 200 OK
Cache-Control: no-cache, private
Content-Type:  application/json
Date:          Wed, 11 Mar 2020 01:12:38 GMT

{'access_token':'blablabla'}

But on the implode in CorsService it has error

[2020-03-11 01:03:53] local.ERROR: implode(): Invalid arguments passed {"userId":1,"exception":"[object] (ErrorException(code: 0): implode(): Invalid arguments passed at /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/asm89/stack-cors/src/Asm89/Stack/CorsService.php:94)
[stacktrace]
#0 [internal function]: Illuminate\\Foundation\\Bootstrap\\HandleExceptions->handleError(2, 'implode(): Inva...', '/Users/bluefitm...', 94, Array)
#1 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/asm89/stack-cors/src/Asm89/Stack/CorsService.php(94): implode(', ', true)
#2 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/fruitcake/laravel-cors/src/HandleCors.php(120): Asm89\\Stack\\CorsService->addActualRequestHeaders(Object(Illuminate\\Http\\JsonResponse), Object(Illuminate\\Http\\Request))
#3 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/fruitcake/laravel-cors/src/HandleCors.php(64): Fruitcake\\Cors\\HandleCors->addHeaders(Object(Illuminate\\Http\\Request), Object(Illuminate\\Http\\JsonResponse))
#4 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Fruitcake\\Cors\\HandleCors->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#5 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php(41): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#6 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\Routing\\Middleware\\SubstituteBindings->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#7 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php(59): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#8 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\Routing\\Middleware\\ThrottleRequests->handle(Object(Illuminate\\Http\\Request), Object(Closure), 60, '1')
#9 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#10 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/laravel/framework/src/Illuminate/Routing/Router.php(683): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))
#11 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/laravel/framework/src/Illuminate/Routing/Router.php(658): Illuminate\\Routing\\Router->runRouteWithinStack(Object(Illuminate\\Routing\\Route), Object(Illuminate\\Http\\Request))
#12 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/laravel/framework/src/Illuminate/Routing/Router.php(624): Illuminate\\Routing\\Router->runRoute(Object(Illuminate\\Http\\Request), Object(Illuminate\\Routing\\Route))
#13 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/laravel/framework/src/Illuminate/Routing/Router.php(613): Illuminate\\Routing\\Router->dispatchToRoute(Object(Illuminate\\Http\\Request))
#14 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(165): Illuminate\\Routing\\Router->dispatch(Object(Illuminate\\Http\\Request))
#15 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\\Foundation\\Http\\Kernel->Illuminate\\Foundation\\Http\\{closure}(Object(Illuminate\\Http\\Request))
#16 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#17 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#18 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#19 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#20 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php(27): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#21 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#22 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php(63): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#23 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#24 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/fruitcake/laravel-cors/src/HandleCors.php(60): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#25 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Fruitcake\\Cors\\HandleCors->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#26 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/fideloper/proxy/src/TrustProxies.php(57): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#27 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Fideloper\\Proxy\\TrustProxies->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#28 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#29 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(140): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))
#30 /Users/bluefitmarketing/Valet-Sites/salt-backend/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(109): Illuminate\\Foundation\\Http\\Kernel->sendRequestThroughRouter(Object(Illuminate\\Http\\Request))
#31 /Users/bluefitmarketing/Valet-Sites/salt-backend/public/index.php(55): Illuminate\\Foundation\\Http\\Kernel->handle(Object(Illuminate\\Http\\Request))
#32 /Users/bluefitmarketing/.composer/vendor/laravel/valet/server.php(158): require('/Users/bluefitm...')
#33 {main}
"} 
[2020-03-11 01:03:53] local.INFO: Handled is: HTTP/1.1 500 Internal Server Error
Cache-Control:         no-cache, private
Content-Type:          application/json
Date:                  Wed, 11 Mar 2020 01:03:53 GMT
X-Ratelimit-Limit:     60
X-Ratelimit-Remaining: 58

Possible bug?

Bluefitdev commented 4 years ago

I'm so dumb, apparently it brings down to the

        if ($this->options['exposedHeaders']) {
            $response->headers->set('Access-Control-Expose-Headers', implode(', ', $this->options['exposedHeaders']));
        }

I set the config as true, didn't really know what it meant.

Set it to false after debugging now its working

Thanks!

barryvdh commented 4 years ago

I've updated the defaults here to make it more clear: https://github.com/fruitcake/laravel-cors/commit/6d46adb112cd844851b81968b8b55b3d12abc43a

Did anyone else have the same problem or debug something?

arjan-vdw commented 4 years ago

Hi,

Having the same problem here. Everything works fine except when Im adding a custom header called 'workspace' to the requests..

Config:

'paths' => ['api/*'], 'allowed_methods' => ['*'], 'allowed_origins' => ['*'], 'allowed_origins_patterns' => [], 'allowed_headers' => ['*'], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => false

Using Laravel 7

barryvdh commented 4 years ago

I've added some tests here: https://github.com/fruitcake/laravel-cors/commit/70b790c92d9a1a0942caf21cfd94d5fa50ce6659 It should work with a wildcard.

Does it work when adding the head manually instead of the wildcard?

barryvdh commented 4 years ago

Hi,

Having the same problem here. Everything works fine except when Im adding a custom header called 'workspace' to the requests..

Config:

'paths' => ['api/*'], 'allowed_methods' => ['*'], 'allowed_origins' => ['*'], 'allowed_origins_patterns' => [], 'allowed_headers' => ['*'], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => false

Using Laravel 7

Did you clear your config? Can you post the exact Request headers as sent by the browser? And the response headers.

Does the Options request succeed? What is the exact error+response?

wassim commented 4 years ago

@barryvdh Having the same problem here. Using the default config on production and doing a request with axios:

await axios.post(`https://mywebsite.com/api/handle`, { data }, {
                headers: {
                    Authorization: 'Bearer ' + process.env.API_TOKEN,
                    Accept: 'application/json',
                }
            })

Access to XMLHttpRequest at 'hidden' from origin 'hidden' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.