Joshua's Cheatsheets
Light
help

JS Networking Requests - Cheatsheet

Fetch

Fetch is a newer browser/web API, that is promise based, and can replace the use of the XMLHttpRequest api.

Resources

What Type Link
MDN Docs Doc Link
MDN Guide Guide Link

Usage

Signature:

/**
* @returns {Promise} that resolves to `Response` object
*/
fetch(resource, options);

Simple demo (from MDN):

fetch('http://example.com/movies.json')
	.then(function(response) {
		return response.json();
	})
	.then(function(myJson) {
		console.log(JSON.stringify(myJson));
	});

What about advanced usage? Options?

Options should be passed as second parameter. Full list is in detail here, and also listed below:

___ ___ ___ ___
method headers body mode
credentials cache redirect referrer
referrerPolicy integrity keepalive signal

Reponse members/methods:

Type Key
Property headers
Property ok
Property redirected
Property status
Property statusText
Property type
Property url
Property useFinalUrl
Property body
Property bodyUsed
Method clone()
Method error()
Method redirect()
Method arrayBuffer()
Method blob()
Method formData()
Method json()
Method text()

Sending POST body

Use FormData:

var formData = new FormData();
formData.append('email', 'foo@example.com');
fetch('https://example.com/checkEmail', {
	method: 'POST',
	body: formData
});

Or, if sending as JSON payload, make sure it is stringified!

fetch('https://example.com/checkEmail', {
	method: 'POST',
	headers: {
		'Content-Type': 'application/json'
	},
	body: JSON.stringify({
		email: 'foo@example.com'
	})
});

Using Headers

There are multiple ways to send custom headers with a fetch request.

Simple object key-pairs

fetch('https://example.com/postJson', {
	method: 'POST',
	headers: {
		'Content-Type': 'application/json'
	},
	body: myJsonPayload
});

Explicit constructor

const myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/json');
fetch('https://example.com/postJson', {
	method: 'POST',
	headers: myHeaders,
	body: myJsonPayload
});

Or, pass object directly to constructor:

const myHeaders = new Headers({
	'Content-Type': 'application/json'
});
fetch('https://example.com/postJson', {
	method: 'POST',
	headers: myHeaders,
	body: myJsonPayload
});

Why use the Headers() interface? There are few benefits; reusability, handy methods, validity checker, etc. Read more here.

CORS

As expected, the fetch() API is subject to the same CORS restrictions that the other browser APIs are. Mainly that if you try to make a cross-origin request, and the response does not have the proper CORS headers, the request will fail.

However, fetch has a specific option for when you want to make a CORS request but don't care about the response. An example of when this might be useful is pinging a server (e.g. with POST) or sending a tracking hit; you might not need to know what the server responds with. This option is setting mode to no-cors, which is also known as using an opaque response.

The response is opaque, because you cannot read its contents.

fetch('http://google.com',{
	mode: 'no-cors'
}).then(function(response){
	console.log(response.type);
	// logs > "opaque"
	return response.text();
}).then(function(t){
	console.log("text = " + t);
	// logs > "text = "
});

Warning: "no-cors" has no impact on CORB and can still be blocked by it.


XMLHttpRequest

@TODO

Resources

What Type Link
MDN Docs Doc Link
MDN Guide Guide Link
Markdown Source Last Updated:
Thu Oct 24 2019 06:03:25 GMT+0000 (Coordinated Universal Time)
Markdown Source Created:
Wed Aug 21 2019 00:46:11 GMT+0000 (Coordinated Universal Time)