Hi, I developed a react app locally with Coinmarketcap API. It was giving me CORS policy error locally too but I managed to handle that error by adding API’s endpoint to the package.json file with a proxy key.
When I deploy my app on netlify, that proxy thing didn’t work anymore. I tried to put heroku.app URL to the beginning of my API but it didn’t work as well. I don’t know back-end so how can I fix this problem?
This is because the rule is proxying everything to the coinmarketcapp site. With React and other SPAs, you need a rule as outlined here to point everything to the index.html in the project.
I see home is the main page of your site, so you do not want to have this route proxying to this other site. What you will want to do is configure an API route e.g.
[[redirects]]
from = "/api/*"
to = "https://pro-api.coinmarketcap.com/v1/:splat"
status = 200
force = true
This rule needs to go before the SPA catch-all rule otherwise it will never get triggered.
Then any call to pro-api.coinmarketcap.com (such as this one) get changed to this format:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at
https://pro-api.coinmarketcap.com/v1/global-metrics/quotes/latest?CMC_PRO_API_KEY=undefined.
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 401.
which means you are still trying to call the URL directly, not using the /api proxy you have configured e.g
Also note the CMC_PRO_API_KEY=undefined at the end. Have you set REACT_APP_API_KEY as an environment variable?
If this API key meant to remain private? If so, using this as you currently are will expose it in your front end. If you wish it to remain private, consider moving the calls to coinmarketcap into a serverless function.
I guess I have configured /api proxy successfully now for the home page. Because now CORS error is gone but it says Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
I set REACT_APP_API_KEY in .env file in my root folder. I know it does not keep it completely private still but for now it is okay for me. I will handle with it after I successfully publish the website
Okay, finally it is kind of working I guess. Now I get 401 error code with my API call which is unauthorized. In my local server, it was working with .env file and API key inside of it. What is the problem now, why does it not read my .env file?
Your project can consume variables declared in your environment as if they were declared locally in your JS files. By default you will have NODE_ENV defined for you, and any other environment variables starting with REACT_APP_ .