skip to Main Content

I am doing building a front end application using react and I am using react-query’s useQuery hook to fetch data. Here is the code

import axios from "axios";
import { useQuery } from "@tanstack/react-query";

 PROXY_URL = "https://cors-anywhere.herokuapp.com/"
 API_URL = "";

export const useProducts = () => {
  const { data, isLoading, error } = useQuery({
    queryKey: ["products"],
    queryFn: async () => {
      try {
        const response = await axios.get(`${PROXY_URL}{API_URL}`);
        return response.data;
      } catch (error) {
        console.log(`Server error: ${error}`);
        throw error;
      }
    },
    retry: 2,
    retryOnMount: true,
  });

  return {
    isLoading,
    error: error || (data && data.error),
    products: data?.data?.products || [],
  };
};

If I use proxy url "https://cors-anywhere.herokuapp.com/" it fetches the data temporarily but not reliable for long term use. I do not have access to the backend api for change cors configuration. This error is really stopping me from building rest of the application. Can someone please help me figure out why I am getting this error and how I can fix it? Thank you in advance for your help.

2

Answers


  1. may be you can add proxy property in your package.json file and assign your initial url to it proxy:https://cors-anywhere.herokuapp.com/ and just use API_URL while fetching the data

    proxy property should contain the back-end server port that is different from the application server port

    package.json

    {
      "proxy":"https://cors-anywhere.herokuapp.com/", /* your backend server port */
      "name": "xyz app",
      "version": "1.0.0",
      "description": "",
      "main": "index.js"
    }
    

    and while fecthing the data

    const response = await axios.get(`${API_URL}`);
    
    Login or Signup to reply.
  2. CORS is ultimately enforced by the browser, so there’s no way to bypass it from the client application alone. You need a separate web server that would fetch the data from the third party API and then return it to your client application with different CORS headers. This is pretty much what https://cors-anywhere.herokuapp.com/ does – it takes the URL you provide it, loads the data from that URL, and then sends it to you with a different CORS configuration.

    Below is a NodeJS + express code snippet from this article that should do the trick for development purposes. Your PROXY_URL would then change to http://localhost:8088/${TARGET_URL}.

    const express = require('express')
    const cors = require('cors')
    const { createProxyMiddleware } = require('http-proxy-middleware')
    
    const app = express()
    app.use(cors())
    app.use(createProxyMiddleware({
      router: (req) => new URL(req.path.substring(1)),
      pathRewrite: (path, req) => (new URL(req.path.substring(1))).pathname,
      changeOrigin: true,
      logger: console
    }))
    
    app.listen(8088, () => {
      console.info('proxy server is running on port 8088')
    })
    

    The code snippet above is from this article.

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