/* eslint-disable no-console */
'use strict';
{
function getText() {
fetch('sample.txt')
.then(res => res.text())
.then(data => {
document.getElementById('output').innerHTML = data;
})
.catch(err => console.log(err));
}
function getUsers() {
fetch('users.json')
.then(res => res.json())
.then(data => {
let output = '
Users
';
data.forEach(user => {
output += `
- ID: ${user.id}
- Name: ${user.name}
- Email: ${user.email}
`;
});
document.getElementById('output').innerHTML = output;
});
}
function getPosts() {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(res => res.json())
.then(data => {
let output = 'Posts
';
data.forEach(post => {
output += `
${post.title}
${post.body}
`;
});
document.getElementById('output').innerHTML = output;
});
}
function addPost(e) {
e.preventDefault();
const title = document.getElementById('title').value;
const body = document.getElementById('body').value;
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
Accept: 'application/json, text/plain, */*',
'Content-type': 'application/json',
},
body: JSON.stringify({ title, body }),
})
.then(res => res.json())
.then(data => console.log(data));
}
document.getElementById('getText').addEventListener('click', getText);
document.getElementById('getUsers').addEventListener('click', getUsers);
document.getElementById('getPosts').addEventListener('click', getPosts);
document.getElementById('addPost').addEventListener('submit', addPost);
}