# Firebase Storage 跨域問題 因為clould firestore只能夠儲存資料,所以為了讓網站也可以有圖片,所以使用Storage,檔案上傳的時候還沒有問題,但一遇到讀取,就出現了跨域,為了要解決這個問題,就要進行以下步驟。 小提醒:在用storage的時候要注意,免費的資源是有限制的,如果一旦超過免費配額,可是會被收費的唷!但做簡單的sideProject是沒問題! [cloud Firestore收費方式](https://cloud.google.com/firestore/pricing?hl=zh-tw) --- 以下開始流程: ### 1.安裝gsutil:  ### 2.進行身分驗證: 安裝完畢後會啟動`gcloud init`的指令初始化,並且出現以下這端文字問你是否要登入 ``` Welcome! This command will take you through the configuration of gcloud. Your current configuration has been set to: [default] To continue, you must login. Would you like to login (Y/n)? ``` 按Y或Enter繼續登入,會直接跳出瀏覽器讓你輸入帳密。登入完成,進到以下畫面就代表成功囉!  回到終端機上,gsutil會抓到目前你 firebase上有那些專案,選擇你要的專案進去 ### 3.配置跨資源設定檔 編寫完儲存在桌面,取名為 **cors.json** ``` = javascript //Google提供的範例 [ { "origin": ["ORIGIN"], "method": ["METHOD"], "responseHeader": ["HEADER"], "maxAgeSeconds": MAX-AGE } ] //自己編寫的設定檔 [ { "origin": ["http://localhost:5000/","http://127.0.0.1:5500/"], "method": ["GET"], "maxAgeSeconds": 3600 } ] ``` - ORIGIN是允許與此存儲分區進行跨域資源共享的網域。例如https://example.appspot.com。 - METHOD是允許與此存儲分區進行跨域資源共享的HTTP方法。例如GET或PUT。 - HEADER是允許與此存儲分區進行跨域資源共享的標頭。例如Content-Type。 - MAX-AGE是允許瀏覽器在必須重複預檢請求之前發出請求的秒數。例如3600。 ### 4.配置跨域共享資源 在終端機上打指令,放入設定檔的檔名,與你個人storage的路徑。  ``` 指令:gsutil cors set {設定檔} gs://{你的firestore路徑}.appspot.com ``` 結果畫面:  這樣就算成功囉! > 需要特別注意終端機打開的位置,如果你有置換或桌面路徑,需要將終端機切道你設定的桌面路徑,才抓的到剛剛設定的 cors.json檔案唷! ### 5.測試接收storage上的圖片  ``` = javascript firebase.storage().ref().child('001.jpg').getDownloadURL() .then((url) => { // `url` is the download URL for 'images/stars.jpg' // This can be downloaded directly: var xhr = new XMLHttpRequest(); xhr.responseType = 'blob'; xhr.onload = (event) => { var blob = xhr.response; }; xhr.open('GET', url); xhr.send(); // Or inserted into an <img> element var img = document.getElementById('myimg'); img.setAttribute('src', url); }) .catch((error) => { // Handle any errors }); ``` 成功了~~  參考連結: - [安裝gsutil](https://cloud.google.com/storage/docs/gsutil_install) - [切換專案的方法](https://cloud.google.com/tpu/docs/storage-buckets?hl=zh-tw) - [配置跨源资源共享 (CORS)](https://cloud.google.com/storage/docs/configuring-cors?hl=zh-cn#gsutil_2) - [通過Web上的Cloud Storage下載文件](https://firebase.google.com/docs/storage/web/download-files) ###### tags: `Firebase`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up