First Express Server
Let's create our first HTTP server with Express and TypeScript.
Installing Express
bash
npm install expressnpm install -D @types/expressBasic Server
typescript
// src/server.tsimport express from 'express'; const app = express();const PORT = process.env.PORT || 3000; // JSON middlewareapp.use(express.json()); // First routeapp.get('/', (req, res) => { res.json({ message: 'Welcome to E-commerce API!' });}); app.listen(PORT, () => { console.log(`🚀 Server running on http://localhost:${PORT}`);});Running the Server
bash
npm run devAccess http://localhost:3000 in the browser.
HTTP Methods
typescript
// GET - Fetch dataapp.get('/products', (req, res) => { res.json([{ id: 1, name: 'iPhone' }]);}); // POST - Create dataapp.post('/products', (req, res) => { const { name, price } = req.body; res.status(201).json({ id: 2, name, price });}); // PUT - Update completelyapp.put('/products/:id', (req, res) => { const { id } = req.params; res.json({ id, ...req.body });}); // DELETE - Removeapp.delete('/products/:id', (req, res) => { res.status(204).send();});Request and Response
typescript
app.get('/products/:id', (req, res) => { // URL parameters const { id } = req.params; // Query string (?page=1&limit=10) const { page, limit } = req.query; // Request body (POST, PUT) const body = req.body; // Request headers const auth = req.headers.authorization; // JSON response res.status(200).json({ success: true, data: { id, page, limit } });});HTTP Status Codes
| Code | Meaning |
|---|---|
| 200 | Success |
| 201 | Created |
| 204 | No content |
| 400 | Bad request |
| 401 | Unauthorized |
| 404 | Not found |
| 500 | Server error |
Summary
- ✅ Express server running
- ✅ HTTP methods (GET, POST, PUT, DELETE)
- ✅ Parameters, query string and body
- ✅ Standardized responses
Next lesson: Routes and Middlewares! 🚀