0

I uploaded some pdf files in firebase storage and trying access the pdf url and giving user to downlaod the respective file on click of the download file button , but its giving me CORS policy error onclick of download file button.

this is code BookDetails.js

import React, { useEffect, useState } from "react";
import styles from "./Bookdetails.module.scss";
import { Link, useParams } from "react-router-dom";
import { db } from "./../../../Firebase/config";
import { doc } from "firebase/firestore";
import { getDoc } from "firebase/firestore";
import { toast } from "react-toastify";
import spinnerImg from "../../../Assets/spinner.jpg";

const BookDetails = () => {
  const { id } = useParams();

  const [book, setBook] = useState(null);

  const getBook = async () => {
    const docRef = doc(db, mycollectionName, id);
    const docSnap = await getDoc(docRef);
    if (docSnap.exists()) {
      // console.log("Document data:", docSnap.data());
      const obj = {
        id: id,
        ...docSnap.data(),
      };
      setBook(obj);
    } else {
      toast.error("BOOK NOT FOUND ");
    }
  };

  const downloadFileUrl = (url) => {
    fetch(url)
      .then((response) => response.blob())
      .then((blob) => {
        const blobUrl = window.URL.createObjectURL(new Blob([blob]));
        const parts = url.split("/");
        const fileName = parts[parts.length - 1].split("?")[0];
        const cleanedFileName = fileName
          .replace(/^[\d]+/, "")
          .replace(/%20/g, " ")
          .trim();
        const aTag = document.createElement("a");
        aTag.href = blobUrl;
        aTag.setAttribute("Download", cleanedFileName);
        aTag.click();
        aTag.remove();
      });
  };

  useEffect(() => {
    getBook();
  }, []);

  return (
    <section>
      <div className={`container ${styles.book}`}>
        <h2>Book Details</h2>
        <div>
          <Link to="#/books">⬅ Back to Homepage</Link>
        </div>
        {book === null ? (
          <img src={spinnerImg} alt="Loading....." />
        ) : (
          <>
            <div className={styles.details}>
              <div className={styles.img}>
                <img src={book.imageUrl} alt={book.name} />
              </div>
              <div className={styles.content}>
                <h3>{book.name}</h3>
                <p className={styles.author}>Author : {book.author}</p>
                <p>{book.desc}</p>
                <p>
                  Category : <b>{book.category}</b>
                </p>
                <p>
                  Language : <b>{book.language}</b>
                </p>
                <p>
                  Publisher : <b>{book.publisher}</b>
                </p>
                {book.file && (
                  <button
                    onClick={() => {
                      downloadFileUrl(book.file);
                    }}
                  >
                    Download File
                  </button>
                )}
              </div>
            </div>
          </>
        )}
      </div>
    </section>
  );
};

export default BookDetails;

This is the image of error enter image description here

I want to solve this error but can't able to solve it . Can anyone tell me how to solve CORS policy error from firebase.

Thank you !!

Just A Guy
  • 49
  • 4

1 Answers1

0

Try to get URL not directly but with Firebase tools:

import { getStorage } from 'firebase/storage';
import { FirebaseStorage, getDownloadURL, ref } from 'firebase/storage';
import firebaseApp from '../path-to-your-firebaseApp';

const firebaseStorage = getStorage(firebaseApp);

// Please check below whether `${book.file}.pdf` produces the correct file name.
// ref(firebaseStorage) - link to the Storage root.
getDownloadURL(ref(firebaseStorage, `${book.file}.pdf`))
      .then((url) => {
        // This can be downloaded directly:
        const xhr = new XMLHttpRequest();
        xhr.responseType = 'blob';
        xhr.onload = () => {
          const blob = xhr.response;
          const link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.target = '_blank';
          link.download = `Yourfile.pdf`;
          link.click();
        };
        xhr.open('GET', url);
        xhr.send();
      })
      .catch((error) => console.error(error));

Please check the next guide to enable CORS for a Firestore database

Artur A
  • 7,115
  • 57
  • 60