const bookForm = document.getElementById('bookForm');
const bookList = document.getElementById('bookList');
// Function to fetch all books from the backend
const fetchBooks = async () => {
const response = await fetch('http://localhost:3000/books');
const books = await response.json();
return books;
};
// Function to render the book list
const renderBooks = async () => {
bookList.innerHTML = '';
const books = await fetchBooks();
books.forEach((book) => {
const li = document.createElement('li');
li.textContent = `${book.title} by ${book.author}`;
bookList.appendChild(li);
});
};
// Function to add a new book
const addBook = async (event) => {
event.preventDefault();
const title = document.getElementById('title').value;
const author = document.getElementById('author').value;
await fetch('http://localhost:3000/books', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ title, author }),
});
renderBooks();
bookForm.reset();
};
// Event listener for form submission
bookForm.addEventListener('submit', addBook);
// Initial render of books
renderBooks();
The code snippet is making a POST request to 'http://localhost:3000/books' with the provided data (title and author) in JSON format, and waiting for the response before proceeding.
The code defines an asynchronous function named `fetchBooks` that fetches data from a backend endpoint (`http://localhost:3000/books`) using the Fetch API. It then parses the response as JSON and returns the resulting books data.