PROBLEM SOLVED. I did a little bit of digging in the node_module folder turns out the problem comes from the react-file-viewer package I was using which is deprecated and no longer updated by it's creator.
accessing file from laravel api storage with reactjs
Hello everyone,
I'm creating a website using a laravel api in the backend and reactjs as the frontend. I've been stuck in a problem for the past hour that I can't seem to solve. It's displaying a file stored in the laravel api from my frontend I get an error when trying to display it :
when trying to display an image I get :
Access to image at 'http://localhost:8000/storage/resources/wait.png' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
And when trying to get another type of file (pdf, docx, ...) I get :
Access to XMLHttpRequest at 'http://localhost:8000/storage/resources/review.pdf' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Here is my controller code in the backend :
public function index()
{
try {
$user = auth()->userOrFail();
$alldata =[] ;
foreach ($user->Followed as $course) {
$data['id']=$course->id;
$data['name']=$course->name;
$data['description']=$course->description;
$data['user_id']=$course->user_id;
$data['rating']=$course->rating;
$data['created_at']=$course->created_at;
$data['updated_at']=$course->updated_at;
$data['Resources']=$course->Resources;
foreach ($course->Resources as $resource) {
$url = Storage::url('resources/'.$resource->attachment);
$resource->attachment= $url;
}
array_push($alldata,$data);
}
return response()->json(['CoursesResources' => $alldata]);
} catch (\Tymon\JWTAuth\Exceptions\UserNotDefinedException $e) {
abort(401);
}
}
And on my front end :
resourceDisplayHandler = (res) => {
let resource = {
path: 'http://localhost:8000' + res.attachment,
type: res.type
}
console.log(resource);
this.setState({displayedResource: resource, showModal: true});
}
if (this.state.showModal) {
modal = <Modal width='60' height='300px'>
<FileViewer
fileType={this.state.displayedResource.type}
filePath={this.state.displayedResource.path}
onError={this.onError}/>
</Modal>
}
I have already done : php artisan storage:link and used the asset() method in the backend none of them worked.
Thank you guys in advance for your help.
Please or to participate in this conversation.