Blog>
Snippets

Fetching Binary Data Cross-Origin

Use Fetch API to retrieve binary data, such as an image or a file, from a cross-origin resource and handle the response as a Blob.
// URL for the cross-origin resource
const url = 'https://example.com/image.png';

// Fetch the resource
fetch(url, {
    method: 'GET', // GET request to retrieve the data
    mode: 'cors' // Set mode to 'cors' to attempt a cross-origin request
})
.then(response => {
    if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.blob(); // Extract binary data as a Blob object
})
.then(blob => {
    // Use the blob object
    // For example, create an object URL for an <img> element
    const imageObjectURL = URL.createObjectURL(blob);
    document.querySelector('img').src = imageObjectURL;
})
.catch(error => {
    console.error('Fetching binary data failed:', error);
});
This code snippet fetches binary data from a cross-origin resource using the Fetch API. The 'GET' method is used to retrieve the image as a Blob object, and 'cors' mode is specified to handle cross-origin requests. Upon successful fetch, a blob object is received, which is then converted to an object URL to be used as a source for an image element. In case of a failure, an error is logged to the console.