I’m redoing the random quote generator challenge using react instead and I seem to be getting a CORS issue when trying to connect to the API. Keep in mind I didn’t have any trouble using the same url when I did the project in jquery.
I’m trying to redo the Random Quote Generator challenge from freecodecamp using React. When I make an API request to Forismatic using axios, I can’t fetch any data.
A look into the browser console shows that I’m having a CORS issue. How do I get around this issue? Keep in mind, I did the exact same project using jQuery and didn’t have any problems connecting the API.
Hey drhectapus, It’s likely that your request with jQuery was considered a “simple request” and didn’t trigger a “CORS preflight.”
Now that you are using axios, the request may have a property that caused the issue. CORS is a sort of defense mechanism in the browser and on the server to prevent unauthorized requests to domains other than your current one.
What you will want to do is to be explicit in your API request by using the options available to you through axios. This will ensure that you maintain a “simple request.”
See if that does the trick. Otherwise you will need to analyze your request and compare its properties against the criteria in the MDN article to figure out how you’ve triggered the CORS preflight.
A quick note about the server side. It’s common to prohibit these types of requests for security reasons and you can see why - PUT and DELETE by unathenticated/unauthorized users. On the server side, you can allow CORS by adding this to the header response object: ‘Access-Control-Allow-Origin’: ‘*’