skip to Main Content

I’m making a request to cloudinary API from a React & Vite App. I Keep getting these two errors:

Acess to XMLHttpRequest at ‘https://api.cloudinary.com/v1_1/sombra/image/list’ from origin ‘https://7aac-2806-2a0-1400-85b6-f0cb-e8b0-4880-f0ed.ngrok-free.app’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

and

ImageGallery.jsx?t=1688258885347:26 GET https://api.cloudinary.com/v1_1/sombra/image/list net::ERR_FAILED 404 (Not Found) (i checked many times and the cloud name is correct)

This is the component:

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

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

  useEffect(() => {
    const fetchImages = async () => {
      try {
        const response = await axios.get(
          'https://api.cloudinary.com/v1_1/sombra/image/list'
        );

        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;

I tried to make a tunnel since apparently this error is very common and it can be caused by my PC. Also tried to update CORS rules in my vite.config.js file but doesnt seem to work either. This is the code that I’m pasting

 server: {
    proxy: {
      "/api": {
        target: "https://api.cloudinary.com/v1_1/sombra/image/list",
        changeOrigin: true,
        secure: false,
        rewrite: (path) => path.replace(/^/api/, ""),
      },
    },
  },

Please help!!

2

Answers


  1. To resolve the CORS issue, you need to configure the server-side to include the appropriate CORS headers in the API response. However, since you are making a request to the Cloudinary API, you don’t have control over the server-side configuration.

    Here’s how you can modify your code to use a proxy server:

    1. Install the http-proxy-middleware package:
        npm install http-proxy-middleware
    
    1. Update your vite.config.js file with the following code:
        import { defineConfig } from 'vite';
        import { createProxy } from 'http-proxy-middleware';
        
        export default defineConfig({
          server: {
            proxy: {
              '/api': {
                target: 'https://api.cloudinary.com/v1_1/sombra',
                changeOrigin: true,
                secure: false,
                pathRewrite: {
                  '^/api': '/image/list',
                },
                onProxyReq: (proxyReq) => {
                  proxyReq.setHeader('Origin', 'https://7aac-2806-2a0-1400-85b6-f0cb-e8b0-4880-f0ed.ngrok-free.app');
                },
              },
            },
          },
          plugins: [
            createProxy('/api', {
              target: 'https://api.cloudinary.com/v1_1/sombra',
              changeOrigin: true,
              secure: false,
              pathRewrite: {
                '^/api': '/image/list',
              },
              onProxyReq: (proxyReq) => {
                proxyReq.setHeader('Origin', 'https://7aac-2806-2a0-1400-85b6-f0cb-e8b0-4880-f0ed.ngrok-free.app');
              },
            }),
          ],
        });
    
    1. Update your component code as follows:
        import { useEffect, useState } from 'react';
        import axios from 'axios';
        
        const ImageGallery = () => {
          const [images, setImages] = useState([]);
        
          useEffect(() => {
            const fetchImages = async () => {
              try {
                const response = await axios.get('/api');
        
                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;
    

    Hope this would help you.

    Login or Signup to reply.
  2. You need to provide your API_KEY, API_SECRET, and your cloud_name which you can find on the dashboard, and replace it with the values in the URL below

    import axios from 'axios';
    
    const response = await axios.get("https://<API_KEY>:<API_SECRET>@api.cloudinary.com/v1_1/<cloud_name>/resources")

    Here is a link to the documentation: Get resources from cloudinary

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search