HTML - Web CORS: A Beginner's Guide

Hello there, aspiring web developers! Today, we're going to embark on an exciting journey into the world of CORS. Don't worry if you've never heard of it before – by the end of this tutorial, you'll be a CORS expert! So, grab your favorite beverage, get comfortable, and let's dive in!

HTML - Web CORS

What is CORS?

CORS stands for Cross-Origin Resource Sharing. Now, I know that sounds like a mouthful, but let me break it down for you with a fun analogy.

Imagine you're at a fancy restaurant (that's your web browser), and you want to order food from another restaurant across the street (that's a different website). Normally, the fancy restaurant won't allow this because they want you to eat their food only. But with CORS, it's like the fancy restaurant says, "Sure, go ahead and order from across the street!" It's a way for web browsers to safely allow websites to request resources from other websites.

Why do we need CORS?

Back in the early days of the web, browsers had a strict security policy called the Same-Origin Policy. This policy prevented websites from making requests to other domains, which was great for security but not so great for functionality.

As the web evolved, developers needed a way to safely make cross-origin requests. That's where CORS came in, providing a secure method for servers to relax the Same-Origin Policy and allow certain cross-origin requests.

How does CORS work?

CORS works through a series of HTTP headers. When a web page makes a request to a different domain, the browser adds a special header called Origin to the request. The server then responds with headers that tell the browser whether the request is allowed.

Let's look at a simple example:

<!DOCTYPE html>
<html>
<head>
<title>CORS Example</title>
</head>
<body>
<h1>CORS in Action</h1>
<button onclick="makeRequest()">Make Request</button>

<script>
function makeRequest() {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
}
</script>
</body>
</html>

In this example, when you click the button, it tries to fetch data from https://api.example.com/data. If the server at api.example.com has CORS configured correctly, it will include headers in its response that allow your webpage to access the data.

Making a CORS Request

Now, let's dive deeper into how to make a CORS request. We'll use the Fetch API, which is a modern, powerful way to make network requests in JavaScript.

fetch('https://api.example.com/data', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

This code sends a GET request to https://api.example.com/data. The server's response will determine whether the request is successful or not.

If CORS is properly configured on the server, you'll see the data logged to the console. If not, you'll get a CORS error, which might look something like this:

Access to fetch at 'https://api.example.com/data' from origin 'http://yourwebsite.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Don't panic if you see this error! It just means the server isn't configured to allow requests from your website.

Event Handlers in CORS

When working with CORS, it's important to handle both successful responses and errors. Let's modify our previous example to include some event handlers:

<!DOCTYPE html>
<html>
<head>
<title>CORS with Event Handlers</title>
</head>
<body>
<h1>CORS with Event Handlers</h1>
<button onclick="makeRequest()">Make Request</button>
<div id="result"></div>

<script>
function makeRequest() {
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
document.getElementById('result').textContent = JSON.stringify(data);
})
.catch(error => {
console.error('Error:', error);
document.getElementById('result').textContent = 'An error occurred: ' + error.message;
});
}
</script>
</body>
</html>

In this example, we've added event handlers for both successful responses and errors. If the request is successful, we display the data on the page. If there's an error, we show an error message.

CORS Methods

CORS supports various HTTP methods. Here's a table summarizing the most common ones:

方法 描述
GET 從伺服器取得資料
POST 傳送資料到伺服器以建立新的資源
PUT 傳送資料以更新伺服器上的既有資源
DELETE 請求刪除伺服器上的資源
HEAD 與 GET 相似,但只取得 headers,不取得 body
OPTIONS 用來描述目標資源的通訊選項

記住,伺服器必須設定允許這些方法以進行 CORS 請求。

Conclusion

恭喜你!你剛剛踏入了 CORS 的世界。我們已經介紹了 CORS 是什麼,為什麼需要它,以及如何進行基本的 CORS 請求。記住,CORS 是關於讓網絡更加互聯同時保持安全性。

在你繼續網頁開發的旅程中,你會在許多不同的情境中遇到 CORS。不要害怕那些 CORS 錯誤 – 它們只是讓你學習更多關於網絡如何工作的機會!

持續練習,保持好奇心,並且快樂編程!

Credits: Image by storyset