Blog>
Snippets

Sending Credentials with a Cross-Origin Request

Demonstrate the use of credentials: 'include' to send cookies or authentication headers in a cross-origin request.
// Create an instance of Headers to add custom headers if needed
const headers = new Headers();
headers.append('Content-Type', 'application/json');

// Use the fetch API to make the request
fetch('https://example.com/api/resource', {
  method: 'GET', // or 'POST', 'PUT', 'DELETE', etc.
  headers: headers,
  credentials: 'include' // Include credentials like cookies, authorization headers, etc. in the request
})
.then(response => response.json()) // Convert the response data to JSON
.then(data => console.log(data))     // Log the JSON data to the console
.catch(error => console.error('Error:', error)); // Log any errors to the console
This code snippet uses the fetch API to send a cross-origin HTTP request to 'https://example.com/api/resource'. It includes credentials like cookies or authorization headers with the request by setting 'credentials: 'include''. The 'headers' variable is used to set any necessary custom headers, like 'Content-Type'. The response is then converted to JSON and logged to the console, or if there's an error, the error is logged to the console.