This article describes how to set CORS in Google Cloud Storage (GCS) and make it accessible from a web page using fetch etc. The related resources are shown below.
The workflow is shown below.
- Creating a bucket
- Setting permissions
- Uploading an object
- CORS settings
- Coding preparation
- Coding
- Operation check
Go to the GCS Web Console and create the following bucket.
- Bucket name: Arbitrary (Example: gcp-storage-cors-(8 digits date))
- Location type: Region
- Region: asia-northeast1 (Tokyo)
- Storage class: Standard
- Prevent public access: Do not check
- Access control: uniform
- Protective tools: None
Access the details page (object list page) of the created bucket and add the following permissions.
- Principal: allUsers
- Role: Storage Legacy Object Read
Upload the following operation check object by clicking the "Upload file" button on the details page of the created bucket.
- Name: status.json
- Content: {"ok": true}
Run the following command in the terminal to prepare the settings.
touch cors.json
Open cors.json in the editor and enter the following content.
Run the following command in the terminal to set CORS.
gsutil cors set cors.json gs://gcp-storage-cors-00000000
Run the following command to prepare for coding.
mkdir gcp-storage-cors
cd gcp-storage-cors
npm init -y
npm install --save-dev http-server
touch config.json index.html main.js
Open config.json in the editor and enter the public URL of the operation check object. You can also find the public URL from the object details page in the GCS web console.
Click to go to config.example.json
Open index.html in the editor and enter the following content.
Open main.js in the editor and enter the following content.
Run the following command in the terminal to start the web server.
npx http-server -c-1
Go to http://localhost:8080/ in the browser and check that the following text is shown in the web page.
{"ok":true}
It seems that it will take a few minutes for the CORS settings of GCS to be reflected, so if it does not work, please wait a while and try again. Thank you for reading!