My Typical Usage of Node.js and Express
When building web applications, I often use Node.js and Express for server-side programming.
Here’s a glimpse into my typical usage.
Models
Models are used to interact with the database. For instance, I have a Users model to handle user-related data:
import Users from "../models/userModel.js";
Controllers
In my controllers, I define functions to handle requests.
For example, here’s how I handle user registration and login:
import Users from "../models/userModel.js";
import { compareString, createJWT, hashString } from "../utils/index.js";
import { sendVerificationEmail } from "../utils/sendEmail.js";
export const register = async(req, res, next) => {
const { firstName, lastName, email, password } = req.body
if(!(firstName || lastName || email || password)){
next("Provide Required Fields!")
return res.status(400).json({ message: "Provide Required Fields!" });
}
try {
const userExist = await Users.findOne({ email })
if(userExist) {
next("Email Address Already Exists")
return res.status(400).json({ message: "Email Address Already Exists" });
}
const hashedPassword = await hashString(password)
const user = await Users.create({
firstName,
lastName,
email,
password: hashedPassword
})
//send email verification to user
sendVerificationEmail(user, res)
} catch (error) {
console.log(error)
res.status(404).json({ message: error.message })
}
}
export const login = async(req, res, next) => {
\\ some login logic
}
Routes
I use Express Router to define routes. Each route is associated with a specific controller function:
import express from "express"
import { login, register } from "../controllers/authController.js"
const router = express.Router()
router.post("/register", register)
router.post("/login", login)
export default router;
Main Server File
In my main server file, I import the routes and use them in my Express application:
import express from "express";
import router from "./routes/index.js";
const app = express()
app.use(router)
With that, we’ve covered a simplified overview of my typical usage of Node.js and Express for server-side programming.