Skip to main content

JavaScript example

Just three lines of code, as highlighted in the snippet below, are all it takes to integrate mockforme.

mockforme with fetch API

index.html
<!doctype html>
<html>
<head>

<script src="https://cdn.jsdelivr.net/npm/mockforme@4.0.0/dist/mockforme.client.umd.js"></script>
<script>
const TOKEN = "ACCESS_TOKEN";
window.mockforme(TOKEN).run();
</script>

<script>
function getSession() {
fetch("/user/getSession")
.then((res) => res.json())
.then((res) => {
console.log(res);
});
}
</script>
</head>
<body>
Example mockforme - Vanilla JS
<div id="app">
<h1>mockforme</h1>
<p>Click the button to make an AJAX request.</p>
<button onclick="getSession()">Make AJAX Request</button>
</body>
</html>

mockforme with XHR

index.html
<html>
<head>

<script src="https://cdn.jsdelivr.net/npm/mockforme@4.0.0/dist/mockforme.client.umd.js"></script>
<script>
const TOKEN = "ACCESS_TOKEN";
window.mockforme(TOKEN).run();
</script>
<script>
let xhr = new XMLHttpRequest();
xhr.open('GET', '/user/getSession', false);

xhr.setRequestHeader('Content-Type', 'application/json');
try {
xhr.send();
if (xhr.status === 200) {
console.log(xhr.response);
}
} catch(err) {
alert("Request failed");
}
</script>
</head>
<body></body>
</html>