Node.jsBackend

Build a REST API with Node.js & Express

TT
TopicTrick Team
Build a REST API with Node.js & Express

Express.js is the most popular web framework for Node.js. It simplifies the process of building robust APIs and web applications.

Setting Up the Project

First, initialize a new Node.js project:

bash
1mkdir my-api 2cd my-api 3npm init -y 4npm install express

Creating the Server

Create an index.js file:

javascript
1const express = require('express'); 2const app = express(); 3const PORT = 3000; 4 5app.use(express.json()); 6 7app.get('/', (req, res) => { 8 res.send('Welcome to my API!'); 9}); 10 11app.get('/api/users', (req, res) => { 12 res.json([ 13 { id: 1, name: 'John Doe' }, 14 { id: 2, name: 'Jane Doe' } 15 ]); 16}); 17 18app.listen(PORT, () => { 19 console.log(`Server running on http://localhost:${PORT}`); 20});

Running the Server

Start your server with:

bash
1node index.js

Visit http://localhost:3000/api/users in your browser to see your JSON response!

Conclusion

Express makes routing and middleware handling incredibly intuitive. You've just built the foundation of a modern backend service.