从 React 应用程序将图像上传到 Cloudinary 时出现 CORS 问题

问题描述 投票:0回答:1

我在尝试从 http://localhost:5173 上运行的 React 应用程序将图像上传到 Cloudinary 时遇到了与 CORS 相关的问题。我已在 Cloudinary 上配置了 CORS,在提取请求中包含了必要的标头,并检查了我的 Cloudinary 帐户设置。但是,我仍然面临以下错误:

从源“http://localhost:5173”获取“https://api.cloudinary.com/v1_1//image/upload”的访问已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:响应中“Access-Control-Allow-Credentials”标头的值为“”,当请求的凭据模式为“include”时,该值必须为“true”。

  const formData = new FormData();
    formData.append('upload_preset',"<upload_preset>")
    const handleImageUpload = async () => {
        try {
            const formData = new FormData();
    
            // Populate formData with images
            for (const image of images) {
                formData.append('file', image); // 'file' is a common parameter name for image uploads
            }
    
            // Cloudinary upload endpoint
            const cloudinaryUploadUrl = 'https://api.cloudinary.com/v1_1/<cloud_name>/image/upload';
    
            // Fetch request
            const response = await fetch(cloudinaryUploadUrl, {
                method: 'POST',
                credentials:'include',
                body: formData,
                headers: {
                    
                    'Authorization': 'Bearer CLOUDINARY_key', // Replace with your Cloudinary API key
                },
            });
    
            // Check the response
            console.log(response);
    
            if (response.ok) {
                const data = await response.json();
                console.log(data);
            } else {
                // Handle error response
                console.error('Error uploading images:', response.statusText);
            }
    
        } catch (error) {
            // Handle other errors
            console.error('Error uploading images:', error);
        }
    };
    

我已确保 Cloudinary API 密钥设置在“授权”标头中,并且凭证模式设置为“包含”。

在从 React 应用程序将图像上传到 Cloudinary 时,是否有人遇到过类似的问题,或者可以提供解决此 CORS 问题的见解?

javascript reactjs node.js cloudinary
1个回答
0
投票

Upload API(您根据您尝试调用的端点使用)的请求身份验证是通过身份验证签名完成的,而不是通过Authorization

(与
Admin一起使用)完成API)。因此,您需要删除 Authorization
 标头。此外,您还需要从请求中删除 
credentials:'include',

由于您尝试使用

未签名上传(即仅使用上传预设),因此您不需要生成签名。

此外,您的

formData

 会被覆盖在 
handleImageUpload
 内,并且 
upload_preset
 的值会丢失。您需要将 
formData.append('upload_preset', ...)
 移动到 
handleImageUpload
 内,并确保 
file
upload_preset
 参数随您的请求一起发送到 Cloudinary。您可以通过在发送请求时检查浏览器的网络选项卡来完成此操作。

© www.soinside.com 2019 - 2024. All rights reserved.