A quick reference guide for building APIs with Node.js using Express.
- Setting Up a Basic Node.js Server
- Basic Routing
- Handling JSON and URL-Encoded Data
- Query Parameters and Route Parameters
- Handling Errors
- Middleware
- Connecting to a Database (MongoDB)
- Environment Variables
- CORS Setup
- Authentication with JWT
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.post('/api/data', (req, res) => {
res.send('Data received');
});
app.use(express.json()); // To parse JSON bodies
app.use(express.urlencoded({ extended: true })); // To parse URL-encoded bodies
Query Parameters
app.get('/search', (req, res) => {
const query = req.query.q;
res.send(`Search query: ${query}`);
});
Route Parameters
app.get('/user/:id', (req, res) => {
const userId = req.params.id;
res.send(`User ID: ${userId}`);
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});
const logger = (req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
};
app.use(logger);
const mongoose = require('mongoose');
mongoose.connect('mongodb://Your MongoDB URI', {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => {
console.log('Connected to MongoDB');
}).catch(err => {
console.error('Failed to connect to MongoDB', err);
});
require('dotenv').config();
const dbUri = process.env.DB_URI;
const cors = require('cors');
app.use(cors({
origin: 'http://example.com', // Replace with your client's URL
methods: ['GET', 'POST'],
}));
const jwt = require('jsonwebtoken');
// Generate Token
const token = jwt.sign({ userId: 123 }, 'secretKey', { expiresIn: '1h' });
// Middleware to Verify Token
const verifyToken = (req, res, next) => {
const token = req.header('Authorization').replace('Bearer ', '');
jwt.verify(token, 'secretKey', (err, decoded) => {
if (err) return res.status(401).send('Access Denied');
req.user = decoded;
next();
});
};
app.get('/protected', verifyToken, (req, res) => {
res.send('This is a protected route');
});