I am trying to connect my site to a database. I am using Node.js, Express.js and Mongodb. I have two forms: a donation form and a signup form. Both use different schemas and routes. The donation form works fine, but when I include the signup route, I encounter issues.
So When the signup route is included in the server file:
The donation form submission results in an “Internet Disconnected” error.
The signup form submission results in a 404 Not Found error.
However When the signup route is commented out,the donation form works perfectly.
Why does the donation form work only when the signup route is commented out?And
how can I resolve the 404 error for the signup form and ensure both forms work correctly?
Here is the link to my repository
THE USER ROUTE
const express = require('express');
const User = require('../models/User');
const router = express.Router();
router.post('/signup', async (req, res) => {
try {
const { firstName, lastName, email, password } = req.body;
const user = new User({ firstName, lastName, email, password });
await user.save();
res.status(201).send({ message: "Sign Up successful" });
} catch (error) {
res.status(400).send({ error: "Error signing up" });
}
});
module.exports = router;
THE SERVER
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
const userRoutes = require('./routes/UserRoute'); // Ensure this path is correct
const app = express();
const port = process.env.PORT || 3000;
// Middleware
app.use(bodyParser.json());
app.use(cors());
app.use(express.json());
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/NGO', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log("Connected to MongoDB");
}).catch(err => {
console.error("Could not connect to MongoDB", err);
});
// Define Donation Schema and Model
const donationSchema = new mongoose.Schema({
firstName: String,
lastName: String,
email: String,
phone: String,
donationType: String,
paymentMethod: String,
amount: Number,
date: { type: Date, default: Date.now }
});
const Donation = mongoose.model('Donation', donationSchema);
// Define Donation Route
app.post('/donate', async (req, res) => {
try {
const { firstName, lastName, email, amount, phone, donationType, paymentMethod } = req.body;
const donation = new Donation({
firstName,
lastName,
email,
amount,
phone,
donationType,
paymentMethod
});
await donation.save();
res.status(201).send({ message: "Donation saved successfully" });
} catch (error) {
res.status(400).send({ error: "Error saving donation" });
}
});
// Use User Routes
app.use('/signup', userRoutes);
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
AND THE SCRIPT FILE HANDLING INPUTS
signUpForm.addEventListener('submit', async function (event) {
event.preventDefault();
const userFirstName = document.getElementById('userFirstName').value;
const userLastName = document.getElementById('userLastName').value;
const userEmail = document.getElementById('userEmail').value;
const password = document.getElementById('pwd').value;
const passwordConfirm = document.getElementById('pwdConfirmation').value;
let confirmationMessage = document.getElementById('SignUpConfirmationMessage');
// Validate form data
if (userFirstName && userLastName && userEmail && password === passwordConfirm) {
try {
const response = await fetch('http://localhost:3000/signup', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
firstName: userFirstName,
lastName: userLastName,
email: userEmail,
password: password
})
});
const data = await response.json();
if (response.ok) {
confirmationMessage.textContent = 'Sign up successful!';
signUpForm.reset();
} else {
confirmationMessage.textContent = 'There was an issue processing your request. Please try again';
}
} catch (error) {
confirmationMessage.textContent = 'There was an issue processing your request. Please try again';
}
} else if (password !== passwordConfirm) {
confirmationMessage.textContent = 'Passwords do not match';
document.getElementById('pwd').value = '';
document.getElementById('pwdConfirmation').value = '';
console.log('Passwords do not match');
} else {
console.log('Please fill in all details correctly');
}
});
}
Kama is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.