How to Fix CORS Issues -- I Think

Bridget Amana - Jul 30 - - Dev Community

You all remember the HNG task I talked about when I wrote about my experience using TypeScript for the first time? Well, a few days ago, I decided to just randomly check the project, and the page kept throwing errors. I refreshed like a dozen times, but still nothing. So, I checked the console.log and saw this error:

Access to fetch at 'https://api.timbu.cloud' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Enter fullscreen mode Exit fullscreen mode

I had no idea what it meant. I tried numerous suggestions and solutions, but nothing worked. After extensive research, I finally found a solution that worked for me, and I want to share it with you.

What is CORS?

CORS stands for Cross-Origin Resource Sharing. It’s a security feature implemented by browsers to restrict web pages from making requests to a different domain than the one that served the web page. This is to prevent malicious websites from accessing sensitive information on other sites.

When Does a CORS Issue Occur?

A CORS issue occurs when your front-end (the part of the website you interact with) tries to fetch data from a backend server (where your data is stored) located on a different domain, and the server does not allow it.

How I Solved My CORS Issue

When I faced the CORS issue, I tried several solutions, but nothing worked until I made some changes to my code. Here’s how I solved it:

  • Using Axios for API Requests Initially, my code was making API requests directly within the components using the fetch method. This was how it looked:
   const response = await fetch(`https://api.timbu.cloud`);
Enter fullscreen mode Exit fullscreen mode

This led to CORS issues because the server didn't allow requests from my frontend domain. So, I switched to using Axios, a promise-based HTTP client, to make API requests.

  • Centralizing API Requests Instead of making requests directly within components, I created a separate file to handle all API requests:
   // src/Api/Api.js
   import axios from 'axios';

   const baseUrl = 'https://api.timbu.cloud';

   export const fetchdata = async () => {
       const { data } = await axios.get(`${baseUrl}/data`);
       return data;
   };
Enter fullscreen mode Exit fullscreen mode

This centralized approach ensured all requests were consistent and properly configured.

  • Using Proper Headers Axios automatically handles many aspects of HTTP requests, including setting the right headers, which is crucial for avoiding CORS issues. Here’s how I used Axios in my components:
   import { fetchData } from './Api/Api';

   const MyComponent = () => {
       useEffect(() => {
           const getData = async () => {
               try {
                   const data = await fetchData();
                   console.log(data);
               } catch (error) {
                   console.error('Error fetching data:', error);
               }
           };
           getData();
       }, []);

       return <div>Check the console for data</div>;
   };
Enter fullscreen mode Exit fullscreen mode

Why This Worked

After changing my code, the CORS issue was resolved. Here’s why I think it worked:

  1. By centralizing the API requests, I ensured that all requests were consistent and properly configured, making it easier to manage headers and other settings.
  2. Switching to Axios simplified the process of setting headers and managing requests, which helped in eliminating the CORS issues.

Conclusion

CORS issues can be tricky, but understanding what they are and how to handle them can save you a lot of headaches. However, I might be wrong in my theory, and this might not be the exact reason why it worked. If you have other theories, please feel free to share them in the comments!

Have you encountered a CORS issue before? How did you solve it? Share your experience in the comments!

For further reading, check out these resources:

. . . . . . . . . . .
Terabox Video Player