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>
Related
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.
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?
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.
I've setup a VUE frontend which connects and authenticates perfectly well with a Laravel backend, using sanctum. I'm able to login and successfully retrieve the logged in user by visiting /api/user. I believe I've followed all the config steps stated in the documentation.
Here is sanctum.php config for stateful domains:
'stateful' => explode(
',',
env(
'SANCTUM_STATEFUL_DOMAINS',
'localhost,localhost:3000,localhost:8080,127.0.0.1,127.0.0.1:8080,::1'
)
), //this is what is in my env SANCTUM_STATEFUL_DOMAINS=app.foo-bar.test:8080
//my laravel backend is running on foo-bar.test
Here is my session.php config:
'domain' => env('SESSION_DOMAIN', null), //in my .env I have: SESSION_DOMAIN=.foo-bar.test
I have the sanctum middleware setup in http/kernel.php, and I'm using auth:sanctum in my routes
Here is my cors.php config:
'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', 'logout'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
and in my vue frontend, I've configured axios to use the following
axios.defaults.baseURL = 'http://foo-bar.test';
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
axios.defaults.withCredentials = true;
As I mentioned, I'm able to successfully login, and even visit /api/user. All works fine,
But when I make a post request to: api/users/multiple,
I get the CORS error: Access to XMLHttpRequest at 'http://foo-bar.test/api/users/multiple' from origin 'http://app.foo-bar.test:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I'm out of ideas, as it seems I've done all the necessary config. Perhaps I'm missing something ? Any help is appreciated.
Kind regards
Add a middleware
php artisan make:middleware Cors
In app/Http/kernel.php paste this in $middleware
protected $middleware = [
\App\Http\Middleware\Cors::class,
....
];
In Middleware/Cors.php now add
public function handle(Request $request, Closure $next)
{
return $next($request)->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods','GET, POST, PUT, PATCH, DELETE,
OPTIONS')
->header('Access-Control-Allow-Headers','Origin, X-Requested-With, Content-
Type, Accept, Authorization');
}
What I came to realise was that this was not actually a CORS issue. If it was a CORS issue, I would not have been able to login, or visit the API that returns the currently logged in user.
What actually happens is that, chrome sometimes fails to report 500 errors on the API and rather returns CORS errors. When I tried making the API call on Firefox, I was able to actually see the 500 error.
Once I resolved the 500 error, the CORS error also stopped appearing in chrome.
What I've seen from this is that the network request error reporting on Firefox is more reliable than that on chrome
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.