Core JavaScript

Fetch with a Request and Headers

This is JavaScript program demonstrates how to fetch with a request object that includes headers.

FetchWithRequestHeaders.html

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width" />
		<title>XoaX.net's Javascript</title>
		<!-- Supply a transparent 1x1 favicon -->
		<link rel="icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=">
		<script type="text/javascript" src="FetchWithRequestHeaders.js"></script>
	</head>
	<body onload="Initialize()">
		<pre style="width:600px;" id="idText"></pre>
	</body>
</html>

FetchWithRequestHeaders.js

async function Initialize() {
	// NOTE: THIS REQUIRES A WEB SERVER TO RUN
	let sFileName = "Job31.txt";

	const kqTextElement = document.getElementById("idText");
	
	const kqRequestHeaders = new Headers();
	// Limit the cached response to a week old
	kqRequestHeaders.set("Cache-Control", "max-age=604800");
	const kqOptions = {
		headers: kqRequestHeaders
	};

	const kqRequest = new Request(sFileName, kqOptions);

	fetch (kqRequest).then((qResponse) =>{
		if (!qResponse.ok) {
			throw new Error(`HTTP error, status = ${qResponse.status}`);
		}
		return qResponse.text();
	}).then((sMessage) => {
		kqTextElement.innerHTML = sMessage
	}).catch((qError) => {
		const qErrorElement = document.createElement("p");
		qErrorElement.appendChild(document.createTextNode(`Error: ${qError.message}`));
		document.body.insertBefore(qErrorElement, kqTextElement);
	});
}
 

Output

 
 

© 2007–2026 XoaX.net LLC. All rights reserved.