You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+Vite调用Cloudinary API遇CORS及404错误求助

解决方案

一、先修复404错误:纠正API端点

你使用的https://api.cloudinary.com/v1_1/sombra/image/list是错误路径,Cloudinary获取图片资源列表的正确API端点为:

https://api.cloudinary.com/v1_1/{cloud_name}/resources/image

对应你的云名称,正确地址是:

https://api.cloudinary.com/v1_1/sombra/resources/image

二、解决CORS问题:正确配置代理+安全调用

Cloudinary的管理API(包括资源列表接口)不允许直接从前端跨域调用,且需要API密钥/签名认证,直接前端调用会暴露敏感信息,同时触发CORS拦截。以下是两种可行方案:

方案1:Vite代理+临时认证(仅测试用,生产不推荐)

1. 修正vite.config.js的代理配置

将target改为Cloudinary API的根地址,而非具体路径:

server: {
  proxy: {
    "/api": {
      target: "https://api.cloudinary.com/v1_1/sombra",
      changeOrigin: true,
      secure: false,
      rewrite: (path) => path.replace(/^\/api/, ""),
      // 测试时添加API密钥(生产环境绝对不能放前端!)
      configure: (proxy) => {
        proxy.on("proxyReq", (proxyReq) => {
          // 替换为你从Cloudinary控制台获取的api_key
          proxyReq.path += "?api_key=你的Cloudinary API密钥";
        });
      },
    },
  },
},

2. 修改前端组件的请求路径

把axios请求地址改为代理路径:

import { useEffect, useState } from 'react';
import axios from 'axios';

const ImageGallery = () => {
  const [images, setImages] = useState([]);

  useEffect(() => {
    const fetchImages = async () => {
      try {
        // 用代理路径替代直接调用Cloudinary API
        const response = await axios.get('/api/resources/image');
        setImages(response.data.resources);
      } catch (error) {
        console.error('Error fetching images:', error);
      }
    };

    fetchImages();
  }, []);

  return (
    <div>
      <h1>Image Gallery</h1>
      <div>
        {images.map((image) => (
          <img
            key={image.public_id}
            src={image.secure_url}
            alt={image.public_id}
          />
        ))}
      </div>
    </div>
  );
};
export default ImageGallery;

方案2:后端处理API调用(生产环境推荐)

  1. 搭建简单后端接口(如Node.js/Express),在后端调用Cloudinary管理API并添加签名认证,避免敏感信息暴露。
  2. 前端通过调用自己的后端接口获取图片列表,彻底解决跨域问题。

关键注意事项

  • Cloudinary管理API必须认证,测试时可临时在代理中添加api_key,但生产环境绝对不能将API密钥放在前端代码或配置文件中。
  • 若仅展示公开图片,可预先获取图片public_id,直接拼接Cloudinary图片URL(https://res.cloudinary.com/sombra/image/upload/{public_id}),无需调用资源列表API。

内容的提问来源于stack exchange,提问作者soul2seul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 16:23:08