Post

JavaScript Fetch

In this post we’ll look at how to use the fetch command in JavaScript in the browser with some common use cases and examples.

  1. Making Requests
  2. Response Data

Making Requests

GET Request

1
fetch('/home');

POST Request

1
2
3
4
5
6
7
8
9
10
// The JSON data that will be sent in our POST request
let apiData = { username: 'username', password: 'password' };

fetch('/login', { 
	method:'POST',
	headers: {
		'Content-Type': 'application/json'
	},
	body: JSON.stringify(apiData)
});

Include Cookies for Cross-Domain Requests

1
2
3
4
5
6
7
8
9
10
11
12
// The current origin is "https://my-domain.com".

// Cookies for "my-domain.com" will be sent in the request.
fetch('/home');

// Cookies for "testing.com" WILL NOT be sent in the request.
fetch('https://testing.com/home');

// Cookies for "testing.com" WILL be sent in the request (assuming the SameSite attribute permits it).
fetch('https://testing.com/home', {
	credentials: 'include'
});


Custom Headers

1
2
3
4
5
6
7
fetch('/home', {
	headers: {
		'Custom-Header-1': 'My Custom Header 1',
		'Custom-Header-2': 'My Custom Header 2',
		'Authorization': ' Bearer myToken',
	},
});


Response Data

Accessing Response Data

Using then/catch/finally

1
2
3
4
5
6
7
fetch('/api/v1/user').then(response => 
	response.json()	// .text() is valid if you want the data as a string instead.
).then(data => {
	console.log(data); // { userId: 1, username: "admin" }
}).catch(err => {
	console.error(err);
});

Using Async & Await

1
2
3
4
let responseData = await fetch('/api/v1/user');
responseData = await responseData.json();

console.log(responseData); // { userId: 1, username: "admin" }

Response Headers & Status

1
2
3
4
5
6
7
8
9
10
11
12
let response = await fetch('/api/v1/user');

// Get the HTTP response code
console.log(response.status);

// Get a single header
console.log(response.headers.get('content-type'));

// Loop over all headers & values
response.headers.forEach((value, header) => {
	console.log(header, value);
});
  • Set-Cookie header will NOT be accessible. It’s removed by the browser for security.
This post is licensed under CC BY 4.0 by the author.