Search code examples
node.jsreactjsexpresshttpcors

CORS Issue with Axios Requests to Ngrok-Hosted Backend API


I am encountering a CORS (Cross-Origin Resource Sharing) issue when making Axios requests from my frontend application to a backend API hosted on Ngrok. The error message I am receiving is "Access to XMLHttpRequest at 'https://fe39-156-220-22-73.ngrok-free.app/api/announcements' from origin 'https://9797-156-220-22-73.ngrok-free.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."

Here is my api.js code:

import axios from 'axios';

const baseURL = 'https://fe39-156-220-22-73.ngrok-free.app'; // Replace with your base URL

const axiosInstance = axios.create({
  baseURL,
  headers: {
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': 'https://9797-156-220-22-73.ngrok-free.app',
  },
});

Here is my function :

 const [announcements, setAnnouncements] = useState()
    const [spin, setSpin] = useState(true)

    const fetchAnnouncements = async () => {

      try{
          const { data } = await axios.get(`/api/announcements`)
          if(data) setSpin(false)
          setAnnouncements(data.json)

      }catch(err){
          console.log(err)
      }
   
  }

Although this code works fine idk why :


export async function getServerSideProps() {
  try {
    // Use the axios instance directly from your api.js file
    const { data } = await axios.get('/api/course');
    return {
      props: {
        courses: data,
      },
    };
  } catch (error) {
    console.error('Error fetching data:', error);
    return {
      props: {
        courses: [], // Return an empty array or handle the error accordingly
      },
    };
  }
}

when i try GET request with postman it works perfectly fine.

I have checked the backend server, and it is running properly. When I use Postman to make requests to the backend API, everything works fine, and I receive the expected data. However, the CORS issue only occurs when making requests from my frontend application hosted on 'https://9797-156-220-22-73.ngrok-free.app' to the Ngrok-hosted backend API at 'https://fe39-156-220-22-73.ngrok-free.app'.

I have tried adding the necessary CORS headers on my backend using app.use(cors()), and I have also tried setting the Access-Control-Allow-Origin header directly in my Axios configuration as shown in the code above, but the issue persists.

I would greatly appreciate any insights or suggestions on how to resolve this CORS issue and successfully make Axios requests from my frontend to the Ngrok-hosted backend API. Thank you in advance for your help!

Error in console

also response header content type is text/html and it should be application/json

response headers


Solution

  • The Problem is due to the thing that you are making axiosInstance but not using it. Export axiosInstance from api.js and then call API from that like this : api.js

     import axios from 'axios';
    
    const baseURL = 'https://fe39-156-220-22-73.ngrok-free.app'; // Replace with your base URL
    
    export const axiosInstance = axios.create({
      baseURL,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': 'https://9797-156-220-22-73.ngrok-free.app',
      },
    });
    

    Your Function

    import axiosInstance from '.././...something'
    
        const fetchAnnouncements = async () => {
    
          try{
              const { data } = await axiosInstance.get(`/api/announcements`)
              if(data) setSpin(false)
              setAnnouncements(data.json)
    
          }catch(err){
              console.log(err)
          }
       
      }
    

    Hope this will solve your problem as now header will include CORS