Setting Custom Headers for Cross-Origin Requests
Illustrate setting custom HTTP headers for a Fetch request to a cross-origin server, such as Authorization.
// Define the URL for the cross-origin request
const url = 'https://cross-origin-server.com/data';
// Create an object with the headers you want to set, including Authorization
const headers = new Headers();
headers.append('Authorization', 'Bearer YOUR_TOKEN_HERE');
headers.append('Content-Type', 'application/json');
headers.append('X-Custom-Header', 'custom-value');
// Set up the fetch request options including method and headers
const fetchOptions = {
method: 'GET',
headers: headers,
mode: 'cors', // Use CORS mode to make a request to a different domain
credentials: 'include' // Include credentials for sites that require authentication
};
// Make the fetch request with custom headers
fetch(url, fetchOptions)
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error('Network response was not ok.');
})
.then(data => console.log('Fetched data:', data))
.catch(error => console.error('Fetching error:', error));
This code sets up a Fetch API request to a cross-origin server by defining custom HTTP headers, including 'Authorization'. It creates a 'Headers' object, appends custom headers, configures the 'fetchOptions' including the mode and credentials, and then sends the fetch request. It handles the response by checking for a successful network response, parsing the JSON, and finally logging data or errors.