Skip to content
This repository has been archived by the owner on Feb 16, 2023. It is now read-only.

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

Closed
baftijarovskiA opened this issue Feb 17, 2020 · 77 comments
Closed

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

baftijarovskiA opened this issue Feb 17, 2020 · 77 comments

Comments

@baftijarovskiA
Copy link

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
Copy link

Experiencing the same problem, what might be the issue

@jekabsmilbrets
Copy link

Same here

@orijmm
Copy link

orijmm commented Feb 19, 2020

Same

@jm21
Copy link

jm21 commented Feb 19, 2020

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

@barryvdh
Copy link
Member

What is your config?

@jm21
Copy link

jm21 commented Feb 19, 2020

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
Copy link
Member

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

@jm21
Copy link

jm21 commented Feb 19, 2020

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

@barryvdh
Copy link
Member

barryvdh commented Feb 19, 2020

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

@jm21
Copy link

jm21 commented Feb 19, 2020

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

@barryvdh
Copy link
Member

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

@George-Krause
Copy link

George-Krause commented Feb 19, 2020

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
Copy link

jm21 commented Feb 19, 2020

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

@barryvdh
Copy link
Member

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
Copy link

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

@phuchnh
Copy link

phuchnh commented Feb 24, 2020

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

@shadowgroundz
Copy link

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

@suppergohan
Copy link

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

@shadowgroundz
Copy link

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

@barryvdh
Copy link
Member

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
Copy link

shadowgroundz commented Feb 24, 2020

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
Copy link
Member

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

@shadowgroundz
Copy link

I use /public/ just only for development

@nalletje
Copy link

nalletje commented Feb 24, 2020

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
Copy link

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
Copy link

miharbi commented Feb 26, 2020

Same error here

@barryvdh
Copy link
Member

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

@sinceow
Copy link

sinceow commented Mar 4, 2020

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

@nalletje
Copy link

nalletje commented Mar 4, 2020

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
Copy link

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,
    ];

@barryvdh
Copy link
Member

Did you allow credentials?

@wassim
Copy link

wassim commented Mar 12, 2020

@barryvdh you mean 'supports_credentials'? It is set to true.

@barryvdh
Copy link
Member

so it's not the default config? Can you please post the exact config + request headers and response headers (as seen in dev tools)

@wassim
Copy link

wassim commented Mar 12, 2020

@barryvdh

Cors.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */

    'paths' => ['api/*'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => false,

    'max_age' => false,

    'supports_credentials' => true,

];

Request headers

Accept: application/json
Authorization: Bearer [hidden_api_token]
Content-Type: application/json;charset=UTF-8
DNT: 1
Referer: https://mywebsite.com/
Sec-Fetch-Dest: empty
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36

Response

Access to XMLHttpRequest at 'https://backend.mywebsite.com/handle' from origin 'https://mywebsite.com' 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.
index.js:35 Error: Network Error
    at LYNF.e.exports (createError.js:17)
    at XMLHttpRequest.p.onerror (xhr.js:91)
xhr.js:183 POST https://backend.mywebsite.com/handle net::ERR_FAILED

@barryvdh
Copy link
Member

I've created an issue template, can you all verify these steps and create a new issue if it doesn't work?

Before you start
[ ] Update to the latest version by running composer update fruitcake/laravel-cors

Check your config
[ ] Double-check your config file with the version from the repo. Make sure the paths property is correctly set. Start by allowing as much as possible.
[ ] Make sure the middleware is added to the global middleware in your Http Kernel (not group)

Clear your caches
Please do these steps again before submitting an issue:
[ ] Clear your config cache php artisan config:clear, route cache (php artisan route:clear) and normal cache (php artisan cache:clear).
[ ] Make sure your permissions are setup correctly (eg. storage is writable)

@yanlinaung30
Copy link

yanlinaung30 commented Apr 15, 2020

In my case, there is no problem when api request to api/products is made. But there is error No 'Access-Control-Allow-Origin' when I try to access api/products/1. I am using Laravel 7 with config/cors.php config.

@yanlinaung30
Copy link

It is solved when I delete the code in controller :3 . So please delete if you use.

dd($product);

@saavedraphp
Copy link

saavedraphp commented Apr 23, 2020

please I have the problem 3 days and I can't find a solution "Laravel 6" that frustrating

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

         axios.get(`http://localhost/estados/pais/${this.selected_pais}`).then((response) => {                
                this.careers = response.data;
            })

protected $middleware = [
\Fruitcake\Cors\HandleCors::class,

'paths'                    => ['api/*'],

'allowed_methods'          => ['*'],

'allowed_origins'          => ['*'],

'allowed_origins_patterns' => [],

'allowed_headers'          => ['*'],

'exposed_headers'          => [],

'max_age'                  => 0,

'supports_credentials'     => false,

error2

@afiqiqmal
Copy link

For my case, After several hours drill down to HandlerCors and CorsService class, the path should be set, else all request will become non-cors

@barryvdh
Copy link
Member

@saavedraphp you allow api/* but your request is /estados ?

@carlomigueldy
Copy link

is there a fix for this issue yet?

@Brandutchmen
Copy link

@carlomigueldy What I did to make this work is code in endpoints within Laravel to use and then use a Guzzle request within Laravel to request the external source.

@carlomigueldy
Copy link

can u show an example? @Brandutchmen

@jardila
Copy link

jardila commented Apr 24, 2020

For my case, After several hours drill down to HandlerCors and CorsService class, the path should be set, else all request will become non-cors

I have the same problem. in my case, i have the route 'api/carga/detail/{id}' with ok response, but the route 'api/carga/uploader' return "No 'Access-Control-Allow-Origin'" error. the only difference in the last one endpoint is that it comes with form-data (files) from the origin.

My cors setting is:

image

image

I hope to find any solution.

@Brandutchmen
Copy link

Brandutchmen commented Apr 24, 2020

@jardila It looks like your api request url is your yoururl/api/cargo/uploader, but your devtools is using port 3000. That might be contributing to your problem. Otherwise, I assume that route is resolving to a controller in Laravel? What does your controller on that one look like?

@jardila
Copy link

jardila commented Apr 24, 2020

@jardila It looks like your api request url is your yoururl/api/cargo/uploader, but your devtools is using port 3000. That might be contributing to your problem. Otherwise, I assume that route is resolving to a controller in Laravel? What does your controller on that one look like?

Thanks @Brandutchmen for your feedback, yes, my app is using the 3000 port but that is not the problem, searching a bit, i find that the problem might be nginx because i had forgotten set 'client_max_body_size' variable (i'm using files very long) and when i put the corresponding value to nginx 'client_max_body_size' the error now is the request send my FormData empty and my controller receive it but generate an error because the file form does not comes with the request.

I will find any solution and will post here if i can do it.

@Brandutchmen
Copy link

@carlomigueldy So here is an sample of a working CORS setup on one of my projects:
Controller:

  public function getData(Request $request)
    {
        $client = new Client();
        $response = $client->request('GET', 'https://jsonplaceholder.typicode.com/users/1'); // Any URL you want.
        $statusCode = $response->getStatusCode();
        $body = $response->getBody()->getContents();
        return $body;
    }

Route (routes /getData to the controller@getData)

Cors config: (This is probably not configured in the most optimal way, just a quick test)

    'paths' => ['*'],

    /*
    * 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' => [
        '*',
        'Content-Type',
        'X-Auth-Token',
        'Origin',
        'Authorization',
        'Access-Control-Allow-Origin',
    ],

    /*
     * 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,
];

Vue Method:

        axios
            .get('/getData')
                .then(function (response) {
                    // handle success
                     console.log(response.data);
                })
        },

@Brandutchmen
Copy link

@jardila Yeah. That does sound like it could be affecting it. I haven't seen client_max_body_size cause cors errors before. Interesting.

@jardila
Copy link

jardila commented Apr 24, 2020

@jardila Yeah. That does sound like it could be affecting it. I haven't seen client_max_body_size cause cors errors before. Interesting.

Effectively, the problem was in my nginx and php configuration. When i configure my nginx and php upload file size in order to allow upload files very long the error disappears. Now the error is in another process but it has nothing to do with cors configuration.

This was in my nginx log error file:

2020/04/24 12:41:40 [error] 18894#18894: *22061 client intended to send too large body: 5874328 bytes, client: 127.0.0.1, server: cobranza.test, request: "POST /api/carga/uploader HTTP/1.1", host: "cobranza.test", referrer: "http://cobranza.test:3000/app/gestion-clientes/cargas/deuda/1"

Thank you so much.

@jardila
Copy link

jardila commented Apr 24, 2020

Please, review this for fix any problem with files in the request.
https://www.cyberciti.biz/faq/fix-client-intended-to-send-too-large-body-xyz-bytes-in-nginx/

@FuriosoJack
Copy link

FuriosoJack commented Apr 24, 2020

¿Sucede con php artisan: serve? ¿Borró el caché (config, etc.) y verificó los permisos para las carpetas de almacenamiento / bootstrap?

in case it works with php artisan serve?
what could be done. Thank you

@Punksolid
Copy link

Punksolid commented Apr 30, 2020

Before you start
I had a setup working with laravel 5.8 but it did a manual upgrade until 7.x, it used to work with
Barryvdh\Cors\HandleCors;

But I changed it to use this following the upgrade guide of laravel
[ ] fruitcake/laravel-cors (v1.0.5 => v1.0.6)

Check your config
My config is set this way

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

[ ] Make sure the middleware is added to the global middleware in your Http Kernel (not group)
Yes it is added in the global

Clear your caches
executed php artisan cache:clear, php artisan config:clear and php artisan route:clear
and chmod -R 777 /storage just for this environment

I saw you were asking to try this with php artisan serve, the problem persists within inside laradock and php artisan serve.

The route im trying to access is
Request URL:http://192.168.1.73:9527/api/sysadmin/v1/login

These are the Request headers

Host: 192.168.1.73:9527
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Referer: http://localhost:9527/
Origin: http://localhost:9527
DNT: 1
Connection: keep-alive

And this the Response headers

TTP/1.1 200 OK
X-Powered-By: Express
Allow: GET,HEAD
Content-Type: text/html; charset=utf-8
Content-Length: 8
ETag: W/"8-ZRAf8oNBS3Bjb/SU2GYZCmbtmXg"
Date: Thu, 30 Apr 2020 01:19:32 GMT
Connection: keep-alive

This is for the OPTIONS verb during the preflight.

I will add a custom middleware for now. I hope this info helps.

UPDATE: Some context, I used to had this package version "barryvdh/laravel-cors": "^0.11.2",
with this configuration file cors.php

    'supportsCredentials' => false,
    'allowedOrigins' => ['*'],
    'allowedOriginsPatterns' => [],
    'allowedHeaders' => ['*'],
    'allowedMethods' => ['*'],
    'exposedHeaders' => [],
    'maxAge' => 0,

@barryvdh
Copy link
Member

So what is X-Powered-By: Express? Is that a Laravel server or expressjs? The endpoint needs the headers.

And please create separate issues.

@saavedraphp
Copy link

I found the solution, the problem was how i put the address. thank you very much.

here the correct

Route::get('estados/pais/', 'UsuarioController@getEstadosByPais');

if (this.selected_pais !="") {
axios.get(http://127.0.0.1:80/estados/pais,
{params: {pais_id: this.selected_pais} }).then((response) => {
this.estados = response.data;
document.getElementById('estado').disabled =false;

            });

SEE THE ERROR IMAGE ABOVE

@zawadsoon
Copy link

zawadsoon commented May 1, 2020

I have a better one.

I had the exact issue with cors. Everything was configured properly, the urls was fine I was hitting right endpoint. But in the middle of development this cors error occured in console.

What i did was permission change on the storage/ directory.

I don't know how permissions impact cors settings, but after setting right permissions everything is fine. It can be specific to my project so if I whenever investigate this I will share my experiences.

So, if you have this issue give a try to chmod 777 on the storeage/ directory
PS: (never use 777 on production)

@abiradak
Copy link

abiradak commented May 26, 2020

HeY Barry I am facing this only in Firefox :(
Here Is my Setup:

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,
    ];
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',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

    ];
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,
    ];
protected $middlewarePriority = [
        \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,
    ];

cors.php

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

console error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://dex.scriptox.in/api/admin/test. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://dex.scriptox.in/api/admin/test. (Reason: CORS request did not succeed).
api.php:

    Route::post('admin/login','CustomLogin@betUserLogin');
    Route::get('logout/{type}','CustomLogin@logOut')->middleware('auth:api');
    Route::group(['prefix' => 'admin/','middleware' => 'auth:api'], function() {
        Route::post('list-user','Admin\AdminController@userList');
     });

@barryvdh
Copy link
Member

And please create separate issues.

@fruitcake fruitcake locked as off-topic and limited conversation to collaborators May 26, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests