0% found this document useful (0 votes)
7 views5 pages

Deep ExpressJS Notes Cosmas

The document provides a comprehensive guide to Express.js, a minimalist web framework for Node.js, covering installation, server creation, middleware, routing, and error handling. It also discusses connecting to MongoDB, creating REST APIs, implementing authentication, and best practices for security and testing. Additionally, it includes deployment strategies and emphasizes the importance of code structure and documentation.

Uploaded by

cosmaskibet444
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views5 pages

Deep ExpressJS Notes Cosmas

The document provides a comprehensive guide to Express.js, a minimalist web framework for Node.js, covering installation, server creation, middleware, routing, and error handling. It also discusses connecting to MongoDB, creating REST APIs, implementing authentication, and best practices for security and testing. Additionally, it includes deployment strategies and emphasizes the importance of code structure and documentation.

Uploaded by

cosmaskibet444
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

1. Introduction to Express.

js
Express.js is a minimalist web framework for Node.js.
It simplifies building robust APIs and web apps.
Key features:
- Middleware support
- Routing system
- Integration with templating engines
- Error handling
- Support for RESTful APIs
- Can be used with any database

2. Installing Node.js & Express


1. Download Node.js from https://nodejs.org
2. Install using your OS package manager or installer
3. Initialize a project: npm init -y
4. Install Express: npm install express
5. Create app.js or server.js for entry point

3. Creating a Basic Server


const express = require('express');
const app = express();
app.get('/', (req, res) => { res.send('Hello World'); });
app.listen(3000, () => console.log('Server running on port 3000'));

4. Middleware
Middleware functions have access to req, res, next.
Types:
- Application-level
- Router-level
- Error-handling
- Built-in (express.json, express.static)
- Third-party (morgan, cors)

Example:
app.use(express.json()); // Parse JSON bodies
app.use((req, res, next) => { console.log(req.url); next(); });

5. Routing in Express
Defines endpoints for HTTP methods.
app.get(path, handler)
app.post(path, handler)
Supports parameters, queries, chaining, regex, etc.

Example:
app.get('/user/:id', (req, res) => res.send(req.params.id));

6. Express Router
Use express.Router() to modularize routes.
Example:
const router = express.Router();
router.get('/', ...);
module.exports = router;
app.use('/api/users', require('./routes/users'));

7. Request and Response


- req.body, req.params, req.query, req.headers
- res.send(), res.json(), res.status(), res.redirect(), res.render()
- Set headers: res.set('Content-Type', 'text/html');

8. Templating Engines
Render HTML dynamically using EJS, Pug, Handlebars.
Set up EJS:
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
res.render('template', { title: 'My App' });

9. Static Files
To serve images, CSS, JS:
app.use(express.static('public'));
Access via http://localhost:3000/style.css if in /public/style.css
10. Forms & Validation
Use express.urlencoded() to parse form data:
app.use(express.urlencoded({ extended: true }));
Validate data manually or use libraries (e.g. express-validator)

11. Environment Variables


Install dotenv: npm install dotenv
Create .env file:
PORT=3000
DB_URI=mongodb://localhost/app
Access in app:
require('dotenv').config();
const port = process.env.PORT;

12. Error Handling


- Catch 404s: app.use((req, res) => res.status(404).send('Not Found'));
- Error middleware:
app.use((err, req, res, next) => {
console.error(err);
res.status(500).send('Server Error');
});

13. Connecting to MongoDB


Install mongoose: npm install mongoose
Connect:
mongoose.connect(process.env.DB_URI).then(...).catch(...);
Define Schema & Model:
const userSchema = new mongoose.Schema({ name: String });
const User = mongoose.model('User', userSchema);

14. REST API with CRUD


Create routes for:
- GET /users
- POST /users
- PUT /users/:id
- DELETE /users/:id
Use MongoDB or any DB with controllers to handle logic.

15. Authentication
- Sessions with express-session
- JWT with jsonwebtoken
Steps:
1. Login user -> generate JWT -> send token
2. Protect routes by verifying token in middleware
3. Logout by destroying token on client

16. Security Best Practices


- Use helmet: app.use(require('helmet')());
- Sanitize input: express-mongo-sanitize, xss-clean
- Limit requests: express-rate-limit
- Enable CORS if needed: app.use(require('cors')());

17. Testing Express Apps


- Use Mocha, Chai, Supertest
Write unit and integration tests:
describe('GET /', () => { it('works', (done) => {
request(app).get('/').expect(200, done); }); });

18. Logging & Debugging


- Use morgan: app.use(require('morgan')('dev'));
- Use debug package: require('debug')('app')

19. Deployment
- Upload project to GitHub
- Use services like Render, Railway, Vercel, or VPS
- Use PM2 to keep app running in background
- Set environment variables on the platform

20. Best Practices


- Structure code using MVC pattern
- Modularize routes, controllers, models
- Use try-catch or async handlers
- Validate all inputs
- Avoid blocking operations
- Document APIs using Swagger or Postman

You might also like