Express – Node.js web application framework – Get started
Last Updated: September 8, 2021
In this lesson, we will study how to install Express web application framework on Node.js and study the basic routing
How to install the Express
npm install express --save
You can have the following code in server.js
const express = require('express') const app = express() const port = 3000 app.get('/', (request, response) => { response.send('Hello from Express!') }) app.listen(port, function () { console.log('Example app listening on port 3000!') })
Now you can start the server
node server.js
Now you can test url http://localhost:3000
in your browser
Really simple to install and run your first piece of code
Routing made easy with Express
By default, Express gives you the routing functionality
This is a very basic router example for a home page. It responds with a “Hello World” message
app.get('/', function (req, res) { res.send('Hello World!') })
This is a router with respond to POST request
app.post('/', function (req, res) { res.send('Got a POST request') })
This is a simple example for form submission, see how routes are working here we have GET and POST here with http://localhost:3000/user
app.post('/user', function (req, res) { let body='' request.on('data',function(data) { body += data; }); request.on('end',function(){ response.writeHead(200, {'Content-Type': 'text/plain'}); response.end('Posted Value is :'+body); }); }) app.get('/user', function (req, res) { var form ="<form method='post'>" form+="<div><label>Product Name </label>" form+="<input type='text' name='key' /></div>" form+="<input type='submit' value='Submit' />" form+="</form>" res.writeHeader(200, {"Content-Type": "text/html"}); res.end(form) })
You can define router for named URL segment like this
app.get('/user/:id', function(req, res) { res.send('user ' + req.params.id); });