Getting Started with Express and Node.js
Node.js is a runtime environment that lets you run JavaScript on the server side. Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications.
โ๏ธ Why Use Node.js?
- ๐ Non-blocking, event-driven architecture
- ๐ฆ Rich ecosystem with npm
- ๐ก Single language (JavaScript) for frontend and backend
- ๐ Real-time data handling
๐งฐ Why Use Express?
- ๐งฑ Minimalist framework
- ๐ง Middleware support
- ๐ Easy routing system
- ๐ Great documentation and large community
๐ง Installation
Create a new Node.js project:
mkdir my-express-app
cd my-express-app
npm init -y
npm install express
๐ Creating Your First Express Server
// app.js
const express = require("express");
const app = express();
const PORT = 3000;
app.get("/", (req, res) => {
res.send("Hello World from Express!");
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Run it:
node app.js
๐ ๏ธ Handling Routes
app.get("/about", (req, res) => {
res.send("About Page");
});
app.post("/submit", (req, res) => {
res.send("Form submitted");
});
๐ฆ Using Middleware
Middleware are functions that have access to request and response objects.
app.use(express.json());
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
๐ Serving Static Files
app.use(express.static("public"));
Put files in the public/
folder to serve them directly.
๐งฉ Using Routers
// routes/userRoutes.js
const express = require("express");
const router = express.Router();
router.get("/", (req, res) => res.send("User Home"));
router.get("/:id", (req, res) => res.send(`User ID: ${req.params.id}`));
module.exports = router;
// In app.js
const userRoutes = require("./routes/userRoutes");
app.use("/users", userRoutes);
๐งช Error Handling
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send("Something broke!");
});
๐ Environment Variables
Install dotenv:
npm install dotenv
Use it:
require("dotenv").config();
const PORT = process.env.PORT || 3000;
๐ Connecting to MongoDB (Quick Example)
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/myapp");
๐ Suggested Project Structure
my-express-app/
โโโ app.js
โโโ routes/
โ โโโ userRoutes.js
โโโ controllers/
โโโ models/
โโโ middlewares/
โโโ public/
โโโ .env