Express JS - basic
What is Express.js ?
At the time of writing, Express (v4.18.3) is Fast, unopinionated, minimalist web framework for Node.js
Bolierplate code (at the minimum)
-
Create a folder and initialize a node project (with default values)
npm init -y -
Install the
express
package and middlewarebody-parser
npm install --save express body-parser -
Create a file called
index.js
and copy the following codeindex.js const express = require('express');const app = express();const port = 3000;// Define a routeapp.get('/', (req, res) => {res.send('Hello, Express!');});// Start the serverapp.listen(port, () => {console.log(`Server is listening at http://localhost:${port}`);}); -
Run the server using following command
node index.js -
The server should be started at
http://localhost:3000
. Upon opening the link, “Hello, Express!” will be served
This is a very minum setup required to start a Express server.
Body Parser middleware
In the above code, body-parser
middleware is installed. This is usually required, in case developing an JSON-based API.
So, we can now extend the server code like below, to get users and set (update) a particular user.
const express = require('express');const bodyParser = require('body-parser');
const app = express();const port = 3000;
// Body Parser middlewareapp.use(bodyParser.urlencoded({ extended: true }));app.use(bodyParser.json());
// Sample datalet users = [ { id: 1, name: 'John Doe' }, { id: 2, name: 'Jane Smith' }, { id: 3, name: 'Bob Johnson' }];
// GET route to retrieve all usersapp.get('/users', (req, res) => { res.json(users);});
// POST route to update user dataapp.post('/users/:id', (req, res) => { const userId = parseInt(req.params.id); const newName = req.body.name;
const userIndex = users.findIndex(user => user.id === userId);
if (userIndex !== -1) { users[userIndex].name = newName; res.json({ message: 'User updated successfully', user: users[userIndex] }); } else { res.status(404).json({ message: 'User not found' }); }});
// Start the serverapp.listen(port, () => { console.log(`Server is listening at http://localhost:${port}`);});
Test the above code
-
To get all users, go to the location
http://localhost:3000/users
-
To post (or update) an user, you can simply use any REST Client extensions or if
cURL
is available, then the following code updates user2curl -X POST http://localhost:3000/users/2 \-H "Content-Type: application/json" \-d '{"name": "New User"}' -
Upon successfull execution, the following result should be shown.
{"message":"User updated successfully","user": { "id":2, "name":"New User" }}