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
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
and while fecthing the data
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}
.The code snippet above is from this article.