Crash Course: From Node.js Basics to Express
Welcome to your crash course on building web applications with Express, starting from Node.js fundamentals. I'll assume you have no prior Node.js knowledge and walk you through the essentials.
Part 1: Node.js Fundamentals
What is Node.js?
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It allows you to run JavaScript on the server side.
Key Concepts:
- Event Loop: Node.js uses an event-driven, non-blocking I/O model
- Modules: Node.js uses a module system (CommonJS) to organize code
- Asynchronous Programming: Heavy use of callbacks, promises, and async/await
Basic Node.js Example
// Import the built-in 'fs' module for file operations
const fs = require('fs');
// Read a file asynchronously
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
console.log('File content:', data);
});
console.log('This runs first because readFile is asynchronous');
Part 2: Setting Up Your Environment
- Install Node.js from nodejs.org
- Verify installation:
node -v
npm -v
Part 3: Introduction to Express
Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
Why Use Express?
- Simplifies routing
- Handles middleware
- Manages requests and responses easily
- Has a large ecosystem of plugins
Part 4: Creating Your First Express App
-
Initialize a new Node.js project:
mkdir my-express-app
cd my-express-app
npm init -y
-
Install Express:
npm install express
-
Create app.js with this basic Express server:
// Import the express module
const express = require('express');
// Create an express application
const app = express();
// Define a port number
const PORT = 3000;
// Define a route for the root URL
app.get('/', (req, res) => {
res.send('Hello World from Express!');
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
-
Run your server:
node app.js
-
Visit http://localhost:3000 in your browser
Part 5: Core Express Concepts
Routing
Express makes it easy to handle different HTTP methods and URLs:
// GET request
app.get('/about', (req, res) => {
res.send('About Page');
});
// POST request
app.post('/submit', (req, res) => {
res.send('Form submitted!');
});
// Route with parameters
app.get('/users/:userId', (req, res) => {
res.send(`User ID: ${req.params.userId}`);
});
Middleware
Middleware functions are functions that have access to the request and response objects:
// Custom middleware
app.use((req, res, next) => {
console.log('Time:', Date.now());
next(); // Pass control to the next middleware
});
// Built-in middleware for parsing JSON
app.use(express.json());
// Built-in middleware for serving static files
app.use(express.static('public'));
Request and Response Objects
Express extends Node's request and response objects with additional methods:
app.get('/example', (req, res) => {
// Request properties
console.log(req.headers); // Request headers
console.log(req.query); // Query parameters
// Response methods
res.status(200).send('OK');
// or
res.json({ message: 'Hello' });
});
Part 6: Building a Simple API
Let's create a simple REST API for a todo application:
const express = require('express');
const app = express();
const PORT = 3000;
// Middleware to parse JSON bodies
app.use(express.json());
// In-memory "database"
let todos = [
{ id: 1, task: 'Learn Node.js', completed: false },
{ id: 2, task: 'Learn Express', completed: false }
];
// GET all todos
app.get('/todos', (req, res) => {
res.json(todos);
});
// GET a specific todo
app.get('/todos/:id', (req, res) => {
const todo = todos.find(t => t.id === parseInt(req.params.id));
if (!todo) return res.status(404).send('Todo not found');
res.json(todo);
});
// POST a new todo
app.post('/todos', (req, res) => {
const newTodo = {
id: todos.length + 1,
task: req.body.task,
completed: false
};
todos.push(newTodo);
res.status(201).json(newTodo);
});
// PUT (update) a todo
app.put('/todos/:id', (req, res) => {
const todo = todos.find(t => t.id === parseInt(req.params.id));
if (!todo) return res.status(404).send('Todo not found');
todo.task = req.body.task || todo.task;
todo.completed = req.body.completed || todo.completed;
res.json(todo);
});
// DELETE a todo
app.delete('/todos/:id', (req, res) => {
const todoIndex = todos.findIndex(t => t.id === parseInt(req.params.id));
if (todoIndex === -1) return res.status(404).send('Todo not found');
todos = todos.filter(t => t.id !== parseInt(req.params.id));
res.status(204).send();
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Part 7: Next Steps
- Templating Engines: Use EJS, Pug, or Handlebars for server-side rendering
- Database Integration: Connect to MongoDB with Mongoose or SQL databases
- Authentication: Implement user authentication with Passport.js
- Error Handling: Add proper error handling middleware
- Environment Variables: Use
dotenv for configuration
- Testing: Write tests with Jest or Mocha
Part 8: Project Structure
As your app grows, organize it like this:
my-express-app/
├── node_modules/
├── public/ # Static files
├── views/ # Templates (if using a templating engine)
├── routes/ # Route definitions
│ ├── index.js
│ └── api.js
├── models/ # Database models
├── controllers/ # Route controllers
├── middlewares/ # Custom middleware
├── config/ # Configuration files
├── app.js # Main app setup
└── package.json
Part 9: Useful Express Methods
app.use(): Mount middleware functions
app.set(): Set application settings
app.get(), app.post(), etc.: Define routes
res.send(): Send a response
res.json(): Send a JSON response
res.status(): Set the HTTP status code
res.redirect(): Redirect to another URL
req.params: Access route parameters
req.query: Access query string parameters
req.body: Access request body (with body-parser middleware)
Part 10: Common Middleware
-
Body Parsing:
app.use(express.json()); // for parsing application/json
app.use(express.urlencoded({ extended: true })); // for parsing form data
-
Static Files:
app.use(express.static('public'));
-
CORS (for API development):
const cors = require('cors');
app.use(cors());
-
Logging:
const morgan = require('morgan');
app.use(morgan('dev'));
Conclusion
You've now learned the basics of Node.js and how to build a web application with Express. From here, you can:
- Explore more advanced Express features
- Learn about database integration
- Implement authentication
- Build full-stack applications by adding a frontend framework
Remember, the best way to learn is by doing - start building small projects to reinforce these concepts!