Fetch API: The Ultimate Guide to CORS and ‘no-cors’

CYBERSPHERE
3 min readApr 22, 2023

--

Do you need to fetch data from a third-party API or server in your web application? If so, you may have encountered Cross-Origin Resource Sharing (CORS) errors that prevent your application from accessing the requested data.

In this blog post, we’ll explore how to use CORS and No-CORS modes in Fetch API to overcome these limitations and successfully fetch data from external sources.

First, let’s understand what CORS is and why it’s important.

CORS is a security feature implemented by web browsers that restricts web pages from making requests to a different domain, protocol, or port than the one that served the web page.

However, it can also be a hindrance when you need to make requests to a third-party API or server from your web application.

The Fetch API provides a way to make HTTP requests from your web application. With Fetch, you can specify the mode of the request using the mode option in the fetch() function.

The mode option can be set to one of four possible values: 'cors', 'no-cors', 'same-origin', or 'navigate'.

In 'cors' mode, the browser includes an Origin header in the request and expects the server to respond with an Access-Control-Allow-Origin header that indicates whether the request is allowed.

If the server responds with the appropriate headers, the browser allows the request to proceed and provides the response to the web page. This mode is useful when making requests to a third-party API or server.

Here’s an example of setting mode to cors

fetch('https://example.com/api/data', {
mode: 'cors'
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
key1: 'value1',
key2: 'value2'
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

In 'no-cors' mode, the browser does not include the Origin header in the request and the server's response is opaque, meaning that its contents cannot be accessed by JavaScript code. This mode is intended for cases where the response from the server is not needed, such as when making a request to a third-party analytics service.

Here’s an example of setting mode to no-cors

fetch('https://example.com/api/data', {
mode: 'no-cors'
})
.then(response => console.log(response))
.catch(error => console.error(error));

Now that we understand how to use CORS and No-CORS modes in Fetch API, let’s talk about when to use them.

As a rule of thumb, you should use 'cors' mode when you need to access data from a third-party API or server, and 'no-cors' mode when you don't need to access the response data.

--

--

CYBERSPHERE

Join Cybersphere, your gateway to tech news and coding tutorials. Explore the endless possibilities of tomorrow with our innovative community.