skip to Main Content

I m making GET request to Backend, with the token, but getting this error

Access to fetch at 'http://XXX.XX.XXX.XX:8067/v1/api/subscriber/list/1/20' from origin 

'http://localhost:5173' has been blocked by CORS policy: Response to preflight request 

doesn't pass access control check: It does not have HTTP ok status.

I have seen the solutions here but None of them worked me. Could you assist me with this issue?

Is this Frontend or Backend issue?

code:

export const getAllSubscribers = async (page, limit) => {
    const token = localStorage.getItem('token').split(":")[1];
  
    const url = api.allSubscribers(page, limit);

    const headers = new Headers();
    headers.append('Authorization', `Bearer ${token}`);
    headers.append('Content-Type', 'application/json');


    try {
      const response = await fetch(url, {
        method: 'GET',
        headers: headers,
      });

      console.log("response------->", response.headers);

      if (!response.ok) {
        throw new Error(`Error fetching subscribers: ${response.statusText}`);
      }
  
      const data = await response.json();
      return data;
    } catch (error) {
      console.error("Error occurred during allSubscribers request:", error);
      throw error;
    }
}

2

Answers


  1. Is this Frontend or Backend issue?

    It’s a backend issue. Your server isn’t responding to the OPTIONS preflight HTTP call with a response with a success code, so the cross-origin call is disallowed. You probably just have the server responding to GET, but certain GET calls (and all POST and similar calls) trigger an OPTIONS call before the GET, a so-called "preflight" call, and your server is apparently not handling that (so it’s returning a 404 or 405 or similar instead, instead of a 200 or similar containing a response with the necessary resource-sharing headers).

    More:

    Login or Signup to reply.
  2. Preflight request an HTTP request of the OPTIONS method, sent before the request itself, in order to determine if it is safe to send it and this request is blocked due to CORS policy occurred when you tried to request to http://XXX.XX.XXX.XX:8067/ from http://localhost:5173.

    If you are using Node.js + Express Backend, I recommend to configure CORS in the backend.

    
    const whitelist = ['http://localhost:5173']
    
    app.use(cors(
      {
        origin:whitelist,
        methods: ["POST", "PUT", "GET", "OPTIONS", "HEAD", "PATCH"],
        credentials:true,
        exposedHeaders: ["Set-Cookie"]
      }
      )
    )
    
    

    Also, you need to configure Fetch headers to accept credentials in Frontend as well.

          const response = await fetch(url, {
            method: 'GET',
            headers: headers,
            credentials: true // Add this line.
          });
    
    

    Hope it will help you.

    Thanks

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