Cross-Origin Resource Sharing (CORS)
Please imagine you're building a spiffy weather application using JavaScript and you want to display live weather data from a popular weather service.
async function fetchWeatherData () {
const response = await fetch(
'https://api.weather.com'
);
console.log('weather', response);
}
You fire up your application, open the browser console, and… nothing. No weather data!!!
What's Happening Behind the Scenes?
Browser performs a Cross-Origin Resource Sharing (CORS) check by default. It's a security mechanism that prevents unauthorized cross-origin requests.
The JavaScript code running on tinyfrontend.com
cannot directly fetch data from api.weather.com
using fetch() or XMLHttpRequest.
This restriction is essential for security—otherwise, malicious sites could wreak havoc by making unauthorized requests to other domains.
Cross-Origin Request
A cross-origin request refers to any situation where a web page attempts to access resources from a server with a different origin than its own.
An origin domain is a combination of 3 parts:
- Protocol: This defines how communication happens between the browser and the server. (e.g,
http
orhttps
) - Domain name: This is the web address you see in the URL bar (e.g.,
tinyfrontend.com
). - Port number: This is a specific port on the server designated for communication. (e.g.,
80
for http,443
for https)
Example
Here are a few examples: