Issue
There's a html page(login.html) which has form whose end point is ./login and method is post.
In the server side index.js is the entry point for the website.
const express=require('express')
const path=require('path')
const mongoose = require('mongoose');
const bodyParser=require('body-parser')
const login=require('./loginServer.js')
const app=express();
const port=3000;
app.use(express.static(path.join(__dirname,'public')))
app.get('/', (req,res)=>{
res.sendFile(path.join(__dirname,'public', 'index.html'));
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/login', login);
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true
},
category: {
type: String,
enum: ['Student', 'Teacher'],
required: true
},
instituteName: {
type: String
},
email: {
type: String,
required: true,
unique: true,
// Add a regex pattern for email validation if needed
},
password: {
type: String,
required: true,
minlength: 6
}
});
const User = mongoose.model('users', userSchema);
module.exports = User;
app.post('/signup', async (req, res) => {
console.log(req.body); // Access form data
const username = req.body.username;
const category = req.body.category;
const instituteName = req.body.schoolName;
const email = req.body.email;
const password = req.body.password;
const userData = { username, category, instituteName, email, password };
// console.log(userData);
try {
await mongoose.connect("mongodb://localhost:27017/manashealth");
// Use await with insertMany to handle the promise
await User.insertMany([userData]);
console.log('User inserted successfully!');
res.send('Welcome!!');
} catch (error) {
if (error.code === 11000) {
console.error('Duplicate key error:', error.errmsg);
res.send(`Account with the email already exists.`);
} else {
// Handle other MongoDB errors
console.error('MongoDB error:', error);
res.status(500).send('Internal Server Error.');
}
}finally{
await mongoose.disconnect();
console.log('mongoose disconnected');
}
});
app.listen(port,'::',()=>{
console.log(`Server is listening at http://localhost:${port}`);
});
I wanted to write the code to handle the ./login in another file(loginServer.js). So I've used express.Router() to handle that end point in LloginServer.js and I've also exported it in the end of the file.
const express=require('express')
const path=require('path')
const mongoose = require('mongoose');
const bodyParser=require('body-parser')
const User = require('./index.js')
const router=express.Router();
router.post('/login', async (req,res)=>{
console.log(req.body);
const email = req.body.email;
const password = req.body.password;
const credentials = {email, password};
try{
await mongoose.connect("mongodb://localhost:27017/manashealth");
const findUser = await User.findOne({email})
if(findUser){
console.log(findUser);
res.send('success');
}else{
console.log('user not found');
}
}catch (error) {
console.error('Error finding user:', error);
res.status(500).json({ message: 'Internal Server Error' });
}finally{
await mongoose.disconnect();
console.log('mongoose disconnected');
}
})
module.exports = router;
Now when i try to login(i.e. click on login) the form is not getting submitted(I think it's not posting).
I tried collect the data from the login.html page through a endpoint ./login, also I handle the endpoint in the backend.
When i run the loginServer.js code I'm encountering this error
PS C:\Users\valli\Desktop\project school\manashealth> node "c:\Users\valli\Desktop\project school\manashealth\loginServer.js" c:\Users\valli\Desktop\project school\manashealth\node_modules\express\lib\router\index.js:469 throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) ^
TypeError: Router.use() requires a middleware function but got a Object at Function.use (c:\Users\valli\Desktop\project school\manashealth\node_modules\express\lib\router\index.js:469:13) at Function. (c:\Users\valli\Desktop\project school\manashealth\node_modules\express\lib\application.js:227:21) at Array.forEach () at Function.use (c:\Users\valli\Desktop\project school\manashealth\node_modules\express\lib\application.js:224:7) at Object. (c:\Users\valli\Desktop\project school\manashealth\index.js:18:5) at Module._compile (node:internal/modules/cjs/loader:1376:14) at Module._extensions..js (node:internal/modules/cjs/loader:1435:10) at Module.load (node:internal/modules/cjs/loader:1207:32) at Module._load (node:internal/modules/cjs/loader:1023:12) at Module.require (node:internal/modules/cjs/loader:1235:19)
Node.js v21.1.0
Solution
It's a routing issue. You are using the router with a /login
path prefix
app.use('/login', login);
But you also added the /login
path to the endpoint itself within the router
router.post('/login', async (req, res)=> {...});
That means that the real path of your endpoint is /login/login
To fix this you could:
- change the endpoint you are calling with your fetch method
fetch('/login/login')
- change the post path to just a slash
router.post('/')
- or what you probably want to do, remove additional path prefix from the router usage:
app.use(login);
Answered By - Krzysztof Krzeszewski
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.