Core JavaScript

Fetch with a Request

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

FetchWithRequest.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="FetchWithRequest.js"></script>
	</head>
	<body onload="Initialize()">
	</body>
</html>

FetchWithRequest.js

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

	const kqBodyElement = document.body;

	const kqRequest = new Request(sFileName);

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

Output

 
 

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