I'm trying to get data back in JSON format as I do in Postman. I'm not 100% sure how postman gets its data from suppling
- GET: URL
- Headers (Key:Value)
- Authorization Type OAuth 2.0 and Access Token.
I've been trying to search how to do this and so far I got this. I don't know what I'm missing.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Bearer Token Authentication</title>
<style>
html {
font-size: 20px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
line-height: 1.7;
}
</style>
</head>
<body>
<h1>Bearer Token Authentication</h1>
<p>When working with tokens, like JWT, you need to send the token to the web server along with each HTTP Request.
</p>
<p><button id="btnFetch">Click to send a Request</button></p>
<script>
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('btnFetch').addEventListener('click', sendReq);
//pretend to get a token after logging in
sessionStorage.setItem('MyUniqueUserToken',
JSON.stringify(
'myTokenkey-sdfsdfsdf'
)
);
});
let sendReq = (ev) => {
let url = 'https://jsonplaceholder.typicode.com/posts';
let token = JSON.parse(sessionStorage.getItem('MyUniqueUserToken'));
let h = new Headers();
h.append('Authentication', `Bearer ${token}`);
h.append('Key', 'x-key-head');
h.append('Value', 'my-value-head');
let req = new Request(url, {
method: 'GET',
mode: 'cors',
headers: h
});
fetch(req)
.then(resp => resp.json())
.then(data => {
console.log(data[0]);
})
.catch(err => {
console.error(err.message);
})
}
</script>
</body>
</html>