This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by cindy-qu
I have been working on my final project for Flatiron School. My project involved using Yelp's API to fetch restaurant information. When fetching a restaurant, I came across the dreaded console error message:
Access to fetch at "yourAPI" from origin 'http://localhost:4000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the request resource.
You have probably come across this before if you have practiced building your own applications with third-party APIs. This blog post will go into detail on what CORS policy is besides a headache when trying to retrieve information.
CORS stands for Cross-Origin Resource Sharing. It is a security policy that means only resources from the same domain, host, and port can interact with the API source. For example, if you try to make a fetch request to https://api.yelp.com/v3/businesses/search, you can't retrieve data from localhost:3000. Only yelp.com would be able to retrieve data from it's server and any subdomains.
There are other situations where some applications need to fetch resources from different servers. This is where CORS comes into place. It enables other websites to access the servers that do not have the same domain, host or port. APIs that have Access-Control-Allow-Origin it means we can make fetch requests from any website.
From MDN "CORS is an HTTP header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources." Modern browsers will block the response to the cross-origin request if the response doesn’t contain the correct “access-control-allow-origin” header.
Workaround
To bypass the CORS restrictions, https://cors-anywhere.herokuapp.com/ was developed. It servers as a proxy and it needs to be prepended to the API endpoint. In my project, I am using axios for my fetch request and prepending cors to my api url. I used an .env file to hide my API key.
import axios from 'axios'
import YELP_KEY from './key'
// proxyURL for CORS approval:
const proxyURL = 'https://cors-anywhere.herokuapp.com/';
const baseURL = 'https://api.yelp.com/v3/businesses'
export default axios.create({
baseURL: proxyURL + baseURL,
//HTTP Header for authorization:
headers: {
Authorization: `Bearer ${YELP_KEY}`
},
// params: {
// limit: 1
// }
})
Other options include hosting your own CORS Anywhere or creating a rails backend to fetch from the yelp API. I am planning to look into both alternatives after my bootcamp ends.
Resources
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by cindy-qu

cindy-qu | Sciencx (2022-12-09T16:33:25+00:00) What is CORS. Retrieved from https://www.scien.cx/2022/12/09/what-is-cors/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.