Learn Node.js & Express with Project in 2 Hours
3 min read
4 hours ago
Published on Nov 26, 2024
This response is partially generated with the help of AI. It may contain inaccuracies.
Table of Contents
Introduction
This tutorial will guide you through building a backend application using Node.js and Express, focusing on a contact management system. By the end of this tutorial, you will have a solid understanding of Express, MongoDB, and JWT authentication, enabling you to create your own projects.
Step 1: Project Setup
- Create a new directory for your project.
- Initialize a new Node.js project by running:
npm init -y
- Install Express and other necessary packages:
npm install express mongoose dotenv jsonwebtoken bcryptjs
Step 2: Create an Express Server
- Create a new file named
server.js
. - Set up a basic Express server:
const express = require('express'); const app = express(); const PORT = process.env.PORT || 5000; app.use(express.json()); app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });
Step 3: Setup Thunder Client for API Testing
- Install the Thunder Client extension in your code editor (like VSCode).
- Use it to test your API endpoints as you build them.
Step 4: Configure Express Router and CRUD Routes
- Create a new folder named
routes
and a filecontactRoutes.js
inside it. - Set up CRUD routes:
const express = require('express'); const router = express.Router(); // CRUD operations router.get('/contacts', getContacts); router.post('/contacts', createContact); router.get('/contacts/:id', getContact); router.put('/contacts/:id', updateContact); router.delete('/contacts/:id', deleteContact); module.exports = router;
Step 5: Create Contact Controller
- Create a new folder named
controllers
and a filecontactController.js
. - Define the CRUD operations within the controller.
Step 6: Handle Multiple HTTP Methods
- Utilize the same route to handle different HTTP methods for cleaner code.
Step 7: Use Middleware for POST Request Body
- Use built-in Express middleware to parse JSON request bodies:
app.use(express.json());
Step 8: Implement Error Handling
- Create a global error handling middleware:
app.use((err, req, res, next) => { res.status(500).json({ message: err.message }); });
Step 9: Set Up MongoDB
- Create a MongoDB account and database.
- Use Mongoose to connect your Express app to the MongoDB database:
const mongoose = require('mongoose'); mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true });
Step 10: Create Mongoose Schema for Contacts
- Define a Mongoose schema for your contacts in a new file
Contact.js
:const mongoose = require('mongoose'); const contactSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true }, phone: { type: String, required: true } }); module.exports = mongoose.model('Contact', contactSchema);
Step 11: Implement CRUD Operations
- Implement the CRUD operations in your
contactController.js
:- Get all contacts
- Create a new contact
- Get a contact by ID
- Update a contact
- Delete a contact
Step 12: User Authentication
- Set up user registration and login routes.
- Create user schema and controller, including password hashing with bcrypt.
Step 13: Implement JWT Authentication
- Generate JWT tokens upon user login:
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: '1h' });
Step 14: Protect Routes
- Create middleware to verify JWT tokens for protected routes.
Step 15: Handle Relationships Between User and Contact
- Update your schemas to establish relationships between users and their contacts.
Conclusion
You have now built a complete contact management backend application using Node.js and Express, integrated with MongoDB and JWT authentication. Consider expanding this project by adding frontend functionality or deploying it online. Keep practicing to deepen your understanding of these technologies!