I wanted to create an employee feedback system which collects feedback and save it to my MongoDB
database. Below are the codes of back-end and front-end. I encountered the following error:
Failed to submit feedback. Please try again later.
The detailed error message is:
api/feedback:1
Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
employee_feedback.html:71 Error: Error saving feedback.
This is a Node.js
code which serves as the server:
const express = require('express');
const mongoose = require('mongoose');
const path = require('path');
const app = express();
const port = process.env.PORT || 3000;
// Serve static files (HTML, CSS, JS)
app.use(express.static(path.join(__dirname, 'public')));
// Use express.json() to parse JSON bodies
app.use(express.json());
// Connect to MongoDB (make sure to have MongoDB installed and running)
mongoose.connect('mongodb://localhost:27017/feedbackDB', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
mongoose.connection.on('error', (err) => {
console.error('MongoDB connection error:', err);
});
// Create a mongoose schema for feedback
const feedbackSchema = new mongoose.Schema({
text: String,
});
const Feedback = mongoose.model('Feedback', feedbackSchema);
// API endpoint to save feedback
app.post('/api/feedback', async (req, res) => {
const feedbackText = req.body.text;
if (!feedbackText) {
return res.status(400).json({ error: 'Feedback text is required.' });
}
try {
const newFeedback = new Feedback({
text: feedbackText,
});
await newFeedback.save();
res.status(201).json({ message: 'Feedback saved successfully.' });
} catch (error) {
console.error('Error saving feedback to the database:', error);
res.status(500).json({ error: 'Error saving feedback to the database.' });
}
});
// Catch-all middleware for handling other routes
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'employee_feedback.html'));
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
The code for the front-end is below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Employee Feedback System</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
}
form {
max-width: 400px;
margin: 20px auto;
}
textarea, button {
padding: 10px;
margin: 5px;
width: 100%;
}
#feedbackList {
max-width: 600px;
margin: 20px auto;
text-align: left;
}
</style>
</head>
<body>
<h1>Employee Feedback System</h1>
<form id="feedbackForm">
<label for="employeeFeedback">Provide your feedback:</label>
<textarea id="employeeFeedback" rows="4" required></textarea>
<button type="button" onclick="submitFeedback()">Submit Feedback</button>
</form>
<div id="feedbackList">
<h2>Employee Feedback</h2>
<ul id="feedbackData"></ul>
</div>
<script>
function submitFeedback() {
var feedbackText = document.getElementById('employeeFeedback').value;
if (feedbackText) {
// Send feedback to the server
fetch('/api/feedback', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ text: feedbackText }),
})
.then(response => {
if (!response.ok) {
throw new Error('Error saving feedback.');
}
return response.json();
})
.then(data => {
alert('Feedback submitted successfully.');
document.getElementById('employeeFeedback').value = '';
})
.catch(error => {
console.error('Error:', error.message);
alert('Failed to submit feedback. Please try again later.');
});
} else {
alert('Please provide feedback before submitting.');
}
}
</script>
</body>
</html>
2
Answers
It looks like you are using
mongodb-Shell
, You need to change the connection string –host
as127.0.0.1:27017
.Try this solution:
https://stackoverflow.com/a/76563265/14895056
If it doesn’t work then update your question and add exactly what error you’re getting. What i mean is show the output of this,