Skip to content
Snippets Groups Projects
Commit dfad545b authored by Fionn's avatar Fionn
Browse files

JavaScript file added to handle axios request to server. Posting book to mongo...

JavaScript file added to handle axios request to server. Posting book to mongo DB database working correctly.
parent 387c4438
No related branches found
No related tags found
No related merge requests found
...@@ -3,6 +3,9 @@ const mongoose = require('mongoose'); ...@@ -3,6 +3,9 @@ const mongoose = require('mongoose');
const app = express(); const app = express();
const path = require('path');
app.use(express.static(path.join(__dirname, '../frontend')));
// Start the server // Start the server
const PORT = 3000; const PORT = 3000;
...@@ -32,8 +35,10 @@ app.listen(PORT, () => { ...@@ -32,8 +35,10 @@ app.listen(PORT, () => {
}); });
// POST route to add a book to the database // POST route to add a book to the database
app.post('/', async (req, res) => { app.post('/submit', async (req, res) => {
try { try {
console.log('Received data:', req.body); // Log the received data
const { title, description, rating } = req.body; const { title, description, rating } = req.body;
// Create a new book instance // Create a new book instance
......
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
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
<body> <body>
<h1> Book Rating Application</h1> <h1> Book Rating Application</h1>
<form action="/submit" method="post"></form> <form id="bookform">
<label for="title">Book Title:</label> <label for="title">Book Title:</label>
<input type="text" id="title" name="title" required placeholder="Enter book title"> <input type="text" id="title" name="title" required placeholder="Enter book title">
<br><br> <br><br>
...@@ -32,6 +32,9 @@ ...@@ -32,6 +32,9 @@
<button type="submit">Submit</button> <button type="submit">Submit</button>
</form> </form>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="book-application.js"></script>
</body> </body>
</html> </html>
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment