簡體   English   中英

NodeJS - 谷歌雲存儲簽名 URL 的 CORS 問題

[英]NodeJS - CORS issue with Google Cloud Storage Signed URLs

我想讓藝術家客戶使用Signed URLs將圖像上傳到 Cloud Storage。

以下后端腳本用於獲取簽名的 url,它位於 Google Cloud 負載均衡器后面:

(這(負載平衡器)會影響什么嗎?)

exports.getSignedUrl = async (req, res) => {

    if (req.method !== 'POST') {
        // Return a "method not allowed" error
        return res.status(405).end();
    }
    try {
        console.log("Getting signed url..");

        const storage = new Storage();
        const bucketName = 'bucket' in req.body ? req.body.bucket : 'gsk-public';
        // Get a reference to the destination file in GCS
        const file = storage.bucket(bucketName).file(req.body.filename);
        // Create a temporary upload URL
        const expiresAtMs = 'expires' in req.body ? req.body.expires : Date.now() + 100; // Link expires in 1 minute
        const configuration = {
            version: 'v4',
            action: req.body.action,
            expires: expiresAtMs
        };
        if ('type' in req.body) {
            configuration.contentType = req.body.type;
        }
        console.log("Got signed url!");
        const url = await file.getSignedUrl(configuration);
        console.log(url);
        return res.send(url[0]);
    }
    catch (err) {
        console.error(err);
        return res.status(500).end();
    }
};

CORS 設置:

[
  {
    "origin": [
      "https://localhost:3000/",
      "https://dreamlouvre-git-development-samuq.vercel.app/"
    ],

    "responseHeader": "*",

    "method": ["GET", "PUT", "POST", "OPTIONS", "HEAD"],

    "maxAgeSeconds": 3600
  }
]

Next.js API端點獲取簽名的url:

import axios from 'axios';
import {config} from '../config';
import { fileTypeToJPG, createQueryString } from '../../../helpers/helpers';
import mime from 'mime';
export default async (req, res) => {
    if(req.method === 'POST'){
        try{
            if(!config.mimeExtensions.some(el => el===mime.getExtension(req.body.type))){
                //throw new Error('The file type of your image is not supported. Following types are supported: jpg, png, bmp and tiff.');
                return res.status(500).json({ statusCode: 500, message: 'Unsupported filetype.' });
            }
            //console.log('file name: ', req.body.filename);
            //console.log('auth header: ', req.headers.authorization);
            const response = await axios.post(`${config.apiBaseUrl}/auth/signedUrl`, req.body, {headers:{"authorization": `Bearer ${req.headers.authorization}`}});
            //console.log("Respdata");
            //console.log(response.data);
            //console.log(response.data[0]);
            const respData = {
                filename: fileTypeToJPG(req.body.filename),
                originalFileName: req.body.filename,
                url: response.data
            };
            return res.status(200).json(respData);
        }catch (err) {
            //console.log(err);
            return res.status('status' in err ? err.status : 500).json({ statusCode: 500, message: err.message });
        }
    }
    else return res.status(403);
};

Next.js 前端代碼放入已簽名的 url:

const badi = {
  type: file.type,
  filename: fileName,
  action: "write",
  bucket: config.bucketOriginal,
};
console.log("upload 3");
const resp = await axios.post(`/api/auth/getSignedUrl`, badi, {
  headers: { authorization: token },
});
console.log("upload 4", resp.data);
await axios.put(resp.data.url, file, {
  headers: { "Content-type": file.type },
});
  • 觀察到的行為:訪問已被 CORS 策略阻止。 控制台日志upload 4和簽名的 url,但簽名的 url 不起作用。

  • 預期行為: put 請求將正常工作。

到期時間出現錯誤,可能導致 CORS 錯誤。 我解決了這個問題:

const expiresAtMs = 'expires' in req.body ? req.body.expires : Date.now() + 100;

對此:

const expiresAtMs = 'expires' in req.body ? req.body.expires : Date.now() + 15*60*1000;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM