I’ve created a login app with node.js. and express.js, as well as with integrating it with the MongoDB database.
Now the issue I got is that when I try to run my server.js file in order to open it with localhost, it doesn’t really work, in terms that the localhost:5000 in my example doesn’t get recognized in the browser. The command I’m using is node server.js, which is correct I believe.
Another thing I’ve noticed is that there is no message in the console when I try to run the app with the node server.js, although in my app code I’ve definitely set it. Now some stuff I’ve tried to implement are defining the allowed IP addresses in MongoDB to be 0.0.0.0/0 + made sure that the network access status is active. In addition to that I’ve double checked that the MONGO URI data is correctly entered with my username and password.
Check out my server.js code:
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const userRoutes = require('./routes/userRoutes');
const app = express();
const PORT = process.env.PORT || 5000;
// Middleware
app.use(bodyParser.json());
// Routes
app.use('/api/users', userRoutes);
// Connect to MongoDB
mongoose
.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log('Connected to MongoDB');
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
})
.catch((err) => {
console.error('Error connecting to MongoDB:', err);
process.exit(1); // Exit if MongoDB connection fails
});
In the .env file I’ve defined the port value and MONGO URI
Also here is my userRoutes.js file:
const express = require('express');
const { registerUser, loginUser, getUserProfile } = require('../controllers/userController');
const { protect } = require('../middleware/authMiddleware');
const router = express.Router();
// Routes
router.post('/register', registerUser);
router.post('/login', loginUser);
router.get('/profile', protect, getUserProfile);
module.exports = router;
Also here is my folder structure:
login-page-app/
├── node_modules/ # Folder for npm packages (auto-generated)
├── routes/ # Folder for route handlers
│ └── userRoutes.js # API routes for user-related actions
├── models/ # Folder for database models
│ └── User.js # User schema model
├── controllers/ # Folder for route logic
│ └── userController.js # Logic for handling user-related actions
├── middlewares/ # Folder for middleware functions
│ └── authMiddleware.js # Middleware for JWT authentication checks
├── .env # Environment variables (MONGO_URI, JWT_SECRET, etc.)
├── package.json # Project metadata and dependencies
├── server.js # Main server file that sets up the app
├── .gitignore # Git ignore file (to exclude node_modules, .env, etc.)