What is Express JS

Express js is the web application framework of nodejs. Express JS or Express is Open Source, fast, unopinionated and minimalist web framework of Node JS used to build Web Applications and APIs.

Express JS is available on npm as express.

Express is a part of MEAN and MERN Stack. MEAN and MERN stacks use JavaScript as primary language to build dynamic web applications. MEAN and MERN Stack simplifies and accelerates web application development.

Express is used by some very popular companies like Uber, IBM, Paypal, Fox Sports

Install ExpressJS

npm i express

or

npm install express

Install express in npm 5 below

npm install express --save

NPM 5.0 and above don't require --save option to add modules in your dependencies available in package.json file. --save option was required only for npm 5 below.


Express JS basics

Express JS simplifies and accelerate web application development. Lets create a hello world app in express using minimum code.

Hello World in Express


const express=require("express");

express().use((req,res)=>{
    res.end('hello world')
}).listen(8080);

Open your web browser and type . If 8080 port is already in use, use another port number like 3000.

setHeader in Express


const express=require("express");
const app=express();
    // register a middleware
app.use((req,res)=>{    
    res.status(200);
    res.setHeader('Content-Type','text/html');
    res.end('<h1>hello world</h1>');
}).listen(8080,()=>{ 
    console.log(`Server running at http://127.0.0.1:8080 `)
});

After every change, you have to run npm src/test.js or npm start to view changes in web browser. Refreshing browser will only refresh client-end.


Use middleware functions

app.use() is used to mount the specific middleware function / functions at specific path. The Route will match any path that follow its path with "/".

middleware functions are functions that have access to request and response and next middleware function in application's request-response cycle.

app.use()

app.use() method is used to call or invoke middleware function (next in example). The below middleware function will be executed for every request to the app.


    app.use((req, res, next)=>{
        console.log('Time: %d', Date.now());
        next();
    })

app.use() middleware with mount route

app.use()middleware function will be executed only for every request to path "/user" path.


    app.use('/user',(req, res, next)=>{
        console.log('Time: %d', Date.now());
        next();
    })

custom middleware functions

custom middleware functions can be called by using app.use() function.


    var myLogger =  (req, res, next)=>{
        console.log('LOGGED');
        next();
};

app.use(myLogger);

Serve static page

To serve static files in express like html, css and javascript files, expressjs use express.static build-in middleware function. Its better to create a public directory or assets directory in src folder of root directory (nodeapp). See example

Directory Structure of express

> nodeapp
    > package-lock.json 
    > package.json    
    > src
        > test.js
        > public
            > img 
                sample.png
            > css
            > js
            > index.html

Static Page using Express


const express=require("express");
const app=express();
    
app.use(express.static('src/public'));

app.use((req,res)=>{
    res.status(200);
    res.setHeader('Content-Type','text/html');
    res.end();
    
}).listen(3000,()=>{ 
    console.log(`Server running at http://127.0.0.1:3000 `)
});    

Create a index.html page in public directory with "Hello Express" in h1 tag.

To open image (in img directory ) in web browser, type


Routing

Routing means how any web application is responding to a client request to a endpoint ( URL or Path) with specific http request like get, post, put and delete.

app or express() have a method with two arguments, path and handler ( callback function). See example. For modular route handler i.e.(express.Router), click ExpressJS Router.


const express=require("express");
const app=express();

app.method(path, handler);   
    
  1. app is instance of express.
  2. method is http method like get or post.
  3. path is path of url
  4. handler is a callback function

Get

http get method is used to get url and respond. get method can handle root path, directory or filename as url. See example


const express=require("express");
const app=express();

app.get('/',(req,res)={
    console.log("get method");
    res.end('get');
});   
    

Set 200 status


const express=require("express");
const app=express();

app.get('/data',(req,res)={
    res.setHeader('Content-Type','text/html');
    res.status(200).send(`<h1>req.url</h1>`);
});   
    

res.send() means both res.write + res.end(). Know more about res.send().

Handle 404 error


const express=require("express");
const app=express();

app.get('/**',(req,res)=>{
    console.log(req.url);
    res.status(404).send(`404, page not found`);
}); 
    

404 wild card handler should be used in the end.


Post

http post method is used to handle post data and its handler. post method can also handle root, directory and file, but without showing the path in browser url tab.


const express=require("express");
const app=express();

app.post('/search',(req,res)={
    console.log("post method);
    res.end('post');
});   
    

Get Response in JSON


const express=require("express");
const app=express();

app.post('/search',(req,res)={
    console.log("post method);
    res.json({"parameters":req.query});
});   
    

Request

HTTP request object has properties for request query string, parameters, body, HTTP Headers etc. We can also use another name for request. By default, the first parameter of callback function of http method is request.

request properties

  1. req.url
  2. req.query
  3. req.params

req.url

/get


app.get('/get',(req,res)=>{
  res.send( req.url);
})    

req.query

req.query return the query parameters in url.

{"parameters":{"q":"node js"}}


app.get('/search?q=node+js',(req,res)=>{
  res.json( {parameters:req.query});
})    
http://127.0.0.1:3000/?q=node+js

req.params

{"id":"apple","name":"iphone"}


app.get("/product/:id/:name", (req,res) => {
    res.send(req.params);
});    
http://127.0.0.1:3000/product/apple/iphone


Response

HTTP response object is the response send by express app when it gets an HTTP request. response is the second parameter of callback function of http method.

Properties and methods of response

  1. res.end
  2. res.send
  3. res.json
  4. res.status
  5. res.redirect

res.end

response.end method will end the response process. response.end quickly ends the response without any data.


app.get('/get',(req,res)=>{
 console.log(req.url);
  res.end();
});    

res.send

response.send method is used to send response data. The parameter of response body can be a Buffer object, a String, an object, or an Array.

response.send is only defined in express. Also res.end() is not required after res.send(). res.send() can be used only once.

Buffer


app.get('/get',(req,res)=>{
    res.send(Buffer.from('buff'));
});    

JSON


app.get('/get',(req,res)=>{
    res.send({ some: 'json' });
});    

html


app.get('/get',(req,res)=>{
    res.send('<p> html content</p>');
});    

404 status


app.get('/get',(req,res)=>{
    res.status(404).send('Page not found');
});    

500 status


app.get('/get',(req,res)=>{
    res.status(500).send({ error: 'Unknown error'});
});    

res.json

res.json is used to send JSON response.


app.get('/search',(req,res)=>{
    console.log('posted data');
    res.json({"parameters":req.query})
});    

res.status

response.status method is used to set http status of response. The parameter of response.status is http status code.


app.get('/',(req,res)=>{
    res.status(400).send('Bad request');
});    

app.get('/**',(req,res)=>{
    res.status(404).send('page not found');
});    

res.redirect

res.redirect is used to redirect url to particular path.


app.get('/admin',(req,res)=>{
    res.redirect('/admin.html');
});    

app.get('/user',(req,res)=>{
    res.redirect('/user.html');
});