I checking some code on NodeJS but here is the error I am getting and notable to resolve it.
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 (D:Reactfeedback-appnode_modulesexpresslibrouterindex.js:469:13)
at Function. (D:Reactfeedback-appnode_modulesexpresslibapplication.js:227:21)
at Array.forEach ()
at Function.use (D:Reactfeedback-appnode_modulesexpresslibapplication.js:224:7)
at Object. (D:Reactfeedback-appserver.js:27:5)
at Module._compile (node:internal/modules/cjs/loader:1378:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1437:10)
at Module.load (node:internal/modules/cjs/loader:1212:32)
at Module._load (node:internal/modules/cjs/loader:1028:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:142:12)Node.js v21.6.2
Here is my auth.js
const express = require('express');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const router = express.Router();
// Register a new user
router.post('/register', async (req, res) => {
const { username, email, password } = req.body;
try {
// Check if the user already exists
let user = await User.findOne({ email });
if (user) {
return res.status(400).json({ msg: 'User already exists' });
}
// Create a new user
user = new User({ username, email, password });
// Hash the password before saving the user
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
await user.save();
// Create and return JWT token
const payload = { user: { id: user.id } };
jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: '1h' }, (err, token) => {
if (err) throw err;
res.json({ token });
});
} catch (err) {
console.error(err.message);
res.status(500).send('Server error');
}
});
// Login a user
router.post('/login', async (req, res) => {
const { email, password } = req.body;
try {
// Check if the user exists
let user = await User.findOne({ email });
if (!user) {
return res.status(400).json({ msg: 'Invalid credentials' });
}
// Compare the entered password with the hashed password
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(400).json({ msg: 'Invalid credentials' });
}
// Create and return JWT token
const payload = { user: { id: user.id } };
jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: '1h' }, (err, token) => {
if (err) throw err;
res.json({ token });
});
} catch (err) {
console.error(err.message);
res.status(500).send('Server error');
}
});
module.exports = router;
This is my server.js
const express = require("express");
const mongoose = require("mongoose");
require('dotenv').config();
const app = express();
app.use(express.json());//middleware
mongoose.connect(process.env.MONGO_URI,{
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => {
console.log('Connected to MongoDB');
}).catch(err => {
console.error('Error connecting to MongoDB:', err.message);
});
app.get('/', (req, res) => {
res.send('Welcome to the Feedback App!');
});
const authRoutes = require('./routes/auth');
console.log("test");
console.log(authRoutes);
console.log("test");
// Routes
app.use('/api/auth', authRoutes); // Add the auth routes
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});