From dfad545bf4790e44c02e429198f589a6602ce9dc Mon Sep 17 00:00:00 2001 From: Fionn <fionnmc123@gmail.com> Date: Wed, 2 Apr 2025 19:57:35 +0200 Subject: [PATCH] JavaScript file added to handle axios request to server. Posting book to mongo DB database working correctly. --- backend/server.js | 7 ++++++- frontend/book-application.js | 26 ++++++++++++++++++++++++++ frontend/submit-book.html | 5 ++++- 3 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 frontend/book-application.js diff --git a/backend/server.js b/backend/server.js index b2efe34..fabaf32 100644 --- a/backend/server.js +++ b/backend/server.js @@ -3,6 +3,9 @@ const mongoose = require('mongoose'); const app = express(); +const path = require('path'); +app.use(express.static(path.join(__dirname, '../frontend'))); + // Start the server const PORT = 3000; @@ -32,8 +35,10 @@ app.listen(PORT, () => { }); // POST route to add a book to the database -app.post('/', async (req, res) => { +app.post('/submit', async (req, res) => { try { + + console.log('Received data:', req.body); // Log the received data const { title, description, rating } = req.body; // Create a new book instance diff --git a/frontend/book-application.js b/frontend/book-application.js new file mode 100644 index 0000000..d03243a --- /dev/null +++ b/frontend/book-application.js @@ -0,0 +1,26 @@ +const form = document.getElementById('bookform'); + +form.addEventListener('submit', async function (e) { + e.preventDefault(); // prevent page reload + + + const title = document.getElementById('title').value; + const description = document.getElementById('description').value; + const rating = document.getElementById('rating').value; + + try { + const response = await axios.post('http://localhost:3000/submit', { + title, + description, + rating + }); + + console.log('Server response:', response.data); + alert('Book submitted successfully!'); + form.reset(); + + } catch (error) { + console.error('Submission failed:', error); + alert('Something went wrong.'); + } +}); \ No newline at end of file diff --git a/frontend/submit-book.html b/frontend/submit-book.html index aca1c38..08a66b4 100644 --- a/frontend/submit-book.html +++ b/frontend/submit-book.html @@ -11,7 +11,7 @@ <body> <h1> Book Rating Application</h1> - <form action="/submit" method="post"></form> + <form id="bookform"> <label for="title">Book Title:</label> <input type="text" id="title" name="title" required placeholder="Enter book title"> <br><br> @@ -32,6 +32,9 @@ <button type="submit">Submit</button> </form> + + <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> + <script src="book-application.js"></script> </body> </html> \ No newline at end of file -- GitLab