Introduction to ExpressJS|| Basics concepts of Express JS

What is ExpressJS?

It is a free open-source web application framework for NodeJS. it is used for designing and building web applications quickly and easily. It is an unopinionated framework which means that it is flexible and allows us to do things in whatever way we wish.

Installation process of ExpresJS:-

  • Download ans install VS code and NodeJS, create package.json by npm init.
  • Open the terminal and write npm install express –save
  • express will be install
npm init
npm install express --save

Creating an HTTP server in Express:-

  • Create a file Index.js
  • Open the documentation of Express and copy the code for hello world program.
  • The app responds with ‘hello world’ for request the root URL (/).
  • For every other path it will respond with 404 not found. ( if you would do it in nodeJS, it will take a lots of if-else statements.

Thunderclient:-

  • It allows us to stay in vs code and do testing of APIs
  • It is a HTTP client extension.

Creating two pages, and rendering:

create index.html and write some content.

in index.js

const express=require('express')
const path=require('path')
const port= 3000
App.get('/',(req,res)=>{res.send('helloworld')})
App.get('/about',(req,res)=>{
res.sendfile(path.join)(__dirname,'index.html')
//App.get lets you define a route
App.listen(port,()=>{
console.log(App listening at http://localhost:${post}')})

Result:-The above code creates two pages one with root URL(‘/’) and the other with(‘/about’). one page render ‘hello world’ and the other will render the content of HTML

Become A Data Scientist In Just 50 Weaks:- Click Here

How to change status code:-

To change status code of /about root.

app.get('/about',(req,res)=>{ res.json('harry'=34)})
//express automatically sets the content type.

Tip:- Install JSON formatter. It makes easy to parse large JSON file.

Serving a folder:- Create a public folder and inside it create an index.html file

//import path module
const path = require('path')
App.use(express.static(path.json(__dirname,'Public')))

It is used to mount specific middleware function(s) at the path which is being specified.

Looking For Paid Internship:- Apply Now

Middleleware:- Function that has access to the request object(req). the response object(res)

Let’s write our own middleware.

Const Pikamiddleware=(req,res,next)=>{console.log(req)next()}
App.use(Pikamiddleware)

Next(): Function in the express router which, when invoked, executes the middleware succeeding the current middleware.

Parameters:

They are named URL segments that are used to capture the values specified at their position in the URL.

eg.

app.get('/hello/:name',(req,res)=>{res.send('Hello world' + req.params.name);})

Creating blog express(Project):-

  • Create a route folder and Blog.js inside it.
  • Create a template folder and create index.html
  • Inside static folder, create index.js

In index.js

const express=require('express')
const path=require('path')
const port= 3000
App.get('/',(req,res)=>{res.send('helloworld')})
App.get('/about',(req,res)=>{
res.sendfile(path.join)(__dirname,'index.html')
//App.get lets you define a route

app.use(Express.static(path.join/__dirname,"static")))
app.use('/', require(path.join/__dirname,'routes/blog.js)))

App.listen(port,()=>{
console.log(App listening at http://localhost:${post}')})

In Blog.js write.

const express= require('express')
const path = require('path')
const router=express.router()
res.sendfile(path.join(__dirname,../templates/index2.html))
//as the file is present in outer folder not inside router folder
})
module.export=router

Result: The content of index2.html will be rendered in our route URL(‘/’). In our case ‘this is site page’ will be printed.

Now serving two pages, we want

  • ‘/’ index.html will be rendered.
  • ‘./blog bloghome.html gets rendered

Create a bloghome.html and we are writing ‘this is blog page’.

Create blogs.js:-

blogs=[{ title:'Python'
         Content:'let Python'
         .................
        ...................
         you can add more.
}
module.export=blogs

In Blog.js

const blogs=require('../data/blogs')
router.get('/blog',(req,res)=>{
res.sendfile(path.join(__dirname,'../templates/Bloghome.html'))}
blogs.foreach(e=>{
console.log(e.title)};

Result:- Bloghome.html gets served In /blog instead of bloghome.html something like the following.

‘/’‘/blog’
HomeBlogs
Blogpost1 (__/blogpost/slug)
Blogpost2

Click and it will serve blogpage.html

To do so open blogs.js

blog=[{
title:"Python"
content:"Learn python"
slug:"Learnning with PC"
}

create blogpage.html and write something, we are writing ‘content here’

In blog.js

router.get('/blogpost/:slug:(req,res)=>{myblog=blogs.filter((e)={
return e.slug=req.params.slug})
console.log(myBlog)
res.sendfile(path.join(__dirname,'../template/blogpage.html)})

Filter:-This method creates a new array with all elements that pass the test implemented by the provided function.

Express Handlebars: Organise data

Pug: template engine for the node and the browser

handlebar:- Helps in JS templating. But we are going to use express handlebars. express.handlebars is an npm package. to install write following command.

npm install express --handlebars

Structure:

  • index.js
  • views –>(Home.handlebars, (Layout folders –>main.handlebars))

main.handlebar:- This file will be rendered in the browser. copy the pre-defined code of the main handlebar.

{{{body}}} —-> Content of Home.handlebar will be served here. And main.handlebar will be served in the browser.

Create Home.handlebars:-

write the following code in index.js

var exphbs=require('express-ha-bars);
app.engine('handlebars',exphbs());
app.set('viewengine','handlebars');

In blog.js

router.get('/',(req,res)=>{
res.render('../home);})

your content of Home.handlebars will be printed in browser.

Get bootstrap in main.handlebars. remember to use href=’/blog’, href=’/’

In blog Home.handlebars (create in views)

use of each helper

{{#each blogs}}
{{this.title}}
{{/each}

In blog.js

router.get('/blog',(req,res)=>{ res.render('blogHome',{blogs:blogs};

Now our content wil be rendered. we can combine link with the rendered text, with help of <a href, and can extend the structure.

thanks for visiting us. We hope you have understood the basics of ExpressJS.

Leave a Comment