'http://localhost:8080' has been blocked by CORS policy Laravel8 - laravel

I am getting this error when I assess an image using html2canvas.
Access to image at 'http://testdomain.com/storage/images/products/user_front.png' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Here is my cors config.
return [
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];
Here the header, when I access the image.
Any one can help me?

Html to canvas uses element in DOM that's why it's requiring a cors from your public folder but laravel does not support that, it only supports cors with api. You need to change your config file.
If you are using nginx use this:
location /storage/ {
add_header 'Access-Control-Allow-Origin' '*';
}
Apache:
<IfModule mod_headers.c>
<FilesMatch "\.(bmp|cur|gif|ico|jpe?g|png|svgz?|webp|pdf)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>
Take note that you need to change the Access-Control-Allow-Origin when deploying to prod to only accept the valid server origin.

Related

Laravel 8 back end and Vue 3 Frontend cors error on deployment (heroku)

My laravel backend and Vue js front end applciations are running on seperate servers. locally it's working very fine, but on deployment i keep getting this error
Access to XMLHttpRequest at 'https://akademiaapi.herokuapp.com/api/country/' from origin 'https://akademiaadmin.herokuapp.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
this is my Laravel configuration for cors and middleware
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
for middleware
protected $middleware = [
\Fruitcake\Cors\HandleCors::class,
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
My vue js configuration
import axios from 'axios'
let Api = axios.create({
baseURL: "https://akademiaapi.herokuapp.com/api"
})
Api.defaults.withCredentials = true
export default Api
i've tried every possible solution shown online, please i really need assistance as this has eating lots of time into my deadline already
i've even added to my route file, but still didn't work
header("Cache-Control: no-cache, must-revalidate");
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type, X-Auth-Token, Origin, Authorization');

CORS preflight request error: Redirect is not allowed for a preflight request [duplicate]

This question already has answers here:
How to resolve 'preflight is invalid (redirect)' or 'redirect is not allowed for a preflight request'
(6 answers)
Closed 1 year ago.
I have Vue3 application with Access-Control-Allow-Origin header set up according documentation
for the package which sends this headers. Every common GET requests have this headers but if the form request send POST request then Access-Control-Allow-Origin header is not included in the response. It throws an error
Access to XMLHttpRequest at 'https://tatrytec.eu/api/article/store/'
from origin 'https://vue.tatrytec.eu' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check:
Redirect is not allowed for a preflight request.
Here is my config/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/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
];
and this is in Kernel.php
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
Here is the code of ArticlesController::store() method which throws an error: https://github.com/camohub/tatrytec.eu/blob/master/app/Http/Controllers/Api/ArticlesController.php#L63
Can somebody tell me please what should I set up in the server code to send required header ? Thanks a lot.
This CORS issue is caused by preflight request redirect which is caused by trailing slash at the end of the request url. It seems the server app try to redirect to canonical url without trailing slash. Many thanks to the author of the answer about this problem.

CORS in Laravel when using fetch to download a file on storage on localhost

Sorry if it looks like I again ask for CORS-configuration in Laravel. But my scenario is alittle bit different and I couldn't find anything helpful yet.
I'm serving my Laravel-Application via php artisan serve --port 80
CORS is configured like this in config/cors.php:
return [
'paths' => ["*"],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];
And enabled in middleware in Kernel.php:
protected $middleware = [
// ...
\Fruitcake\Cors\HandleCors::class,
// ...
];
In my frontend (localhost:8080) I do a simple
const content = await fetch("http://localhost/storage/plans/46718040-5c72-4999-865f-5174a7c59313.png")
but I'm getting the following error:
Access to fetch at 'http://localhost/storage/plans/46718040-5c72-4999-865f-5174a7c59313.png'
from origin 'http://localhost:8080' 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.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Do I have to setup Nginx locally to configure cors for the storage? Or are there any other ideas?
Do I have to setup Nginx locally to configure cors for the storage?
Yes. Your request isn't invoking Laravel at all, the file is being served statically.
Do you need to use fetch to get the content, or can you just set an image source to the file path instead?

Any reason why pre-build cors policy configuration not functioning in Laravel 7 application?

I made a "post" request using axios to the Laravel back-end application. It always throws these errors
after submitting the form :
Access to XMLHttpRequest at 'mydomain' (redirected from 'mydomain') from origin 'mydomain' 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.
before submitting the form :
Cross-Origin Read Blocking (CORB) blocked cross-origin response mydomain with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.
what I have done so far:
cors.php ( config file in laravel )
return [
'paths' => ['api/*','web/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [
'Cache-Control',
'Content-Language',
'Content-Type',
'Expires',
'Last-Modified',
'Pragma',
],
'max_age' => 0,
'supports_credentials' => false,
];
Allow origin and the paths had been changed.
vue js axios request
const result = await this.callApi('post','/user/login', this.data)
callApi method
async callApi(method,url,data){
try {
//axios.defaults.headers.post['Content-Type'] ='application/x-www-form-urlencoded';
// Send a POST request
return await axios({
method: method,
url: url,
data: data
});
} catch (e) {
return e.response
}
},
Thanks for all the viewers.
"composer update" command has solved the problem.

Laravel How to solve Cross-Origin Request Blocked

I want to read a pdf file though the api, but it gives me this error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
after I tried Ammar answer, the error message changes to
Access to fetch the resource from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
this is my cors.php
<?php
return [
'paths' => ['api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'Access-Control-Allow-Origin'=> '*',
'Access-Control-Allow-Headers'=> 'Origin, Content-Type',
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => false,
'max_age' => false,
'supports_credentials' => false,
];
How to solve this error?
I think the PDF file is in the public folder.
So you need to change this line:
'paths' => ['api/*'],
To be like this:
'paths' => ['*'],
Because the public folder path is not prefixed by api prefix group.
If that didn't work. Maybe laravel is not applying the CORS related HTTP headers to the response of the file. So you need to configure Apache or Nginx. Check out this issue:
https://github.com/fruitcake/laravel-cors/issues/163
Update
Try to add this configuration to your webserver:
<Directory /path/to/your/public/folder/>
Header set Access-Control-Allow-Origin "*"
</Directory>

Resources