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' header is present on the requested resource. #481

Closed
raakkan opened this issue Jul 22, 2020 · 34 comments
Closed

Comments

@raakkan
Copy link

raakkan commented Jul 22, 2020

im using this boilerplate Apiato

postman request working and browser request working but axios request not working.

axios setup.

import axios from 'axios';

const api = axios.create({
    baseURL: 'http://api.apiato.test/v1',
    headers: {
        'Access-Control-Allow-Origin': '*',
        'Content-type': 'application/json',
    },
});

api.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

let token = document.head.querySelector('meta[name="csrf-token"]') as HTMLMetaElement;

if (token) {
    api.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

export default api;

error.

Access to XMLHttpRequest at 'http://api.apiato.test/v1/users' from origin 'http://apiato.test' 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.

app.js:1691 Uncaught (in promise) Error: Network Error
    at createError (app.js:1691)
    at XMLHttpRequest.handleError
@davidquon
Copy link

In case it helps others #477 (comment). I'm using the 2.0 version on the server.

@barryvdh
Copy link
Member

How does your config look like?

@davidquon
Copy link

Looks like there is another solution too (at least for my use case) setting supports_credentials to true in cors.php. Hopefully it helps your use case as well.
#477 (comment)

Thanks for the help @barryvdh. 🍻

@RyosukeHashimotoGithub
Copy link

RyosukeHashimotoGithub commented Aug 3, 2020

same problem.

in my case,

/config/cors.php

return [
    'paths' => ['*'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => false,
];

/app/Http/Kernel.php

protected $middleware = [
        \Fruitcake\Cors\HandleCors::class,
        // ...
    ];

routes/web.php

Route::domain(config('app.domain'))->group(function () {
    Route::match(['options', 'post'], 'sample', 'SampleController');
});

Route::domain('sub.' . config('app.domain'))->group(function () {
    Route::view('/', 'sample');
});

sample.blade.php

<script>
  $.ajax({
        url: '/sample',
        type: 'POST',
      }).done(
    // ...
</script>

it's working on local, but not working on lambda by vapor.

@senter-logistics
Copy link

same problem

@KieronWiltshire
Copy link

Same here, subbing to this thread.

@alexaderramos
Copy link

el mismo problema

@linaandres
Copy link

In my case, I solved it by adding

header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, Accept,charset,boundary,Content-Length');
header('Access-Control-Allow-Origin: *');

into routes/api.php

check this link
https://stackoverflow.com/a/63650811

@tnduc
Copy link

tnduc commented Oct 6, 2020

same problem

@pesovski
Copy link

pesovski commented Oct 6, 2020

Same problem. Just to mention I am using Laravel 8, maybe it has some breaking changes.

@celorodovalho
Copy link

Same problem in Laravel 8.
Only works with the @linaandres suggestion.

@manoelsouzaunicef
Copy link

Same problem in Laravel 8.
Only works with the @linaandres suggestion.

Hello @celorodovalho
Were you able to resolve this situation? It would help me a lot

@pesovski
Copy link

pesovski commented Nov 5, 2020

The issue I had wasn't with this package or with Laravel. The issue was that I was stupid.
The routes I tested were echoing content like:
echo $user->toJson();
And it was interrupting the headers.

Once I replaced this with
return response()->json($user)
it started working fine.

Just mentioning here in case someone is making the same dummy mistake.

@celorodovalho
Copy link

@manoelsouzaunicef I had a stupid mistake. I was trying to debug using "dump" in some routes, so the OPTIONS can't handle the response throwing 'Access-Control-Allow-Origin' errors.

@manoelsouzaunicef
Copy link

@manoelsouzaunicef I had a stupid mistake. I was trying to debug using "dump" in some routes, so the OPTIONS can't handle the response throwing 'Access-Control-Allow-Origin' errors.

I got it, brother. But my routes are just toJSON anyway. I'm stuck on that problem. It doesn't even work with @linaandres said. Not if it's related to the laravel version. Thanks a milion

@helderferrari2
Copy link

I solved this problem in Laravel 7 this way:

in cors.php

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

to
'exposed_headers' => ['Authorization'],

@yo-mike
Copy link

yo-mike commented Dec 28, 2020

I've had this problem occasionally, and it usually takes some time to debug.

Today, I realized that my model Observer was failing and dumping some data. This exception was causing my CORS to break.

@toplyb
Copy link

toplyb commented Jan 6, 2021

same problem in Laravel6

@manoelsouzaunicef
Copy link

I noticed these errors when trying to do a very large upgrade. Version 5.3 for a bigger one. The solution was to remove the composer lock, the vendor folder, and redo the entire installation. Also remove caches with artisan cache: clear.

@mguilhermealves
Copy link

Para quem ainda estiver com o problema, entrar no "DevTools" do navegador, aba Application e apertar o botão Clear site data. Isso resolveu pra mim.

@Benyaminrmb
Copy link

I still have this problem in laravelSanctum Laravel 8

@wa05
Copy link

wa05 commented Mar 22, 2021

Every two months CORS is waiting for us in every new setup .. more than 13223298 developers commit suicide every year of f cors problems

@manoelfilho
Copy link

I am having problems with CORS after an upgrade of the Laravel version. Most cases aren't about a real error of CORS. When I active the mode environment to develop and active the logs with debug = true I can see the real errors in storage/logs. In most cases, the problems occurred with permission for storage/logs.

@barryvdh
Copy link
Member

Yeah sorry, it's really hard to debug these problems. I've tried to reproduce any of the cases on Github, but almost all are either misconfigured config (wrong path, old config cached), misconfigured permissions (eg. storage dir not writable), wrong usage (missing middleware), duplicatie headers (eg. nginx/apache/index.php also adding headers), headers already sent (echo/header calls), no proper response (dd()/exit() in the code or some proxy issue (wrong host). If there are actual reproducable errors on a clean Laravel install, I'm happy to take a look.

@johnymanuelli
Copy link

@manoelsouzaunicef I had a stupid mistake. I was trying to debug using "dump" in some routes, so the OPTIONS can't handle the response throwing 'Access-Control-Allow-Origin' errors.

Had the same problem, lol thank you very much

@ajadi473
Copy link

ajadi473 commented May 5, 2021

I still have this problem in laravelSanctum Laravel 8

Have you been able to fix this? I currently have this too

@jeffersonbabuyo
Copy link

@barryvdh - I am using this package and followed the documentation you provided. And it's working so far EXCEPT when I am trying perform a POST/PUT/PATCH request with file upload (binary) I am getting a CORS ERROR No 'Access-Control-Allow-Origin' header is present.

Note that this is not duplicate headers issue because it would throw me the error right when logging-in and I've created the nginx configuration myself. Hope you can enlighten me on this matter.

@amrography
Copy link

amrography commented Aug 18, 2021

As quick solution, you can modify headers in nginx or apache like following

nginx (nginx.conf or valet.conf)

server{
    add_header Access-Control-Allow-Origin *;
}

apache (.htaccess)

server{
    <IfModule mod_setenvif.c>
        <IfModule mod_headers.c>
            Header set Access-Control-Allow-Origin "*"
        </IfModule>
    </IfModule>
}

nginx config file

vi /usr/local/etc/nginx/nginx.conf

or if you are using valet

vi /usr/local/etc/nginx/valet/valet.conf

@nunomazer
Copy link

My problem with CORS where that I was accessing my host with HTTP and not HTTPS, on remote test server.

@MartinLindalHansen
Copy link

@manoelsouzaunicef I had a stupid mistake. I was trying to debug using "dump" in some routes, so the OPTIONS can't handle the response throwing 'Access-Control-Allow-Origin' errors.

Oh my god.... You made my day!
Thanks for pointing in the right direction - at least for my case.

@barryvdh
Copy link
Member

@zeeshan-mehdi
Copy link

hello guyz i found the solution. my configuration is exactly as the documentation says. but the problem was with the app cache.

so i cleared cache

and it worked

command

php artisan config:clear

@Stecken
Copy link

Stecken commented Oct 9, 2021

hello guyz i found the solution. my configuration is exactly as the documentation says. but the problem was with the app cache.

so i cleared cache

and it worked

command

php artisan config:clear

For me it worked creating the middlewares and clearing the cache, thank you!

@afrazahmmad
Copy link

Followed documentation, but having issue in laravel 9.

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