Skip to main content

NodeJS: Express JS

Express JS (MVC)

  • framework/architecture for nodejs (web)
  • express js as Rest API (get, post, put, delete - req. http method).
  • Htpp interaction communication (http req -> request response cycle)
  • middleware
  • input data, process, meaningful output (Web App)
  • npm install express -- save
Note:
- An object is equivalent to Javascript.
- NodeJS is equivalent to the callback.

- ExpressJS is equivalent to Middleware.

Creating Server in NodeJS and http module (Client Server Communication)
1. mkdir firstapp
2. cd firstapp
3. npm init
4. create app.js

Explanation (app.js):

- http module injection
- createServer method (callback function use -> req, res)
- After client and server connection, server will listen and client will request.
(req is always http req.object and res or 2nd argyment is always http response object.)
- req.end (end the request and listen the server (1st arg-> port, 2nd arg-> host and 3rd arg-> callback function.))
- If err -> server listening failed and if not server listening at port 4040 (to acknowledge the server status)


# Express Auto Folder Generator

  1. npm install -g express-generator (one time run)
  2. express folder_name (always run this code to build app)
  3. npm install (to install package mention in package.json)
  4. npm start (or edit "start": "nodemon app.js"- need to install nodemon)
  5. localhost: 3000 (run in browser)

Express 

- Express is routing and middleware web framework.
HTTP Method
  1. Get (default): req.data from a specified resource (create)
  2. Post: send data to the server to create/update (read)
  3. Put: send data to a server to create/ update resource (rename)
  4. Delete: delete specified resource (delete)
#Postman
Postman contains a powerful runtime based on Nodejs that allows you to add dynamic behavior to requests and collections. 
- API Development Environment.
- save, import, export, env., link share
- unique, username, email (null value -> unique)

#Middleware
- ExpressJS is a lightweight, efficient middleware and routing framework.
- Middleware functions are functions that have access to the request object (req) and the response object (res) and the next function in the applications req-response cycle.
- Everything in the express is middleware.
Example:
var a = function (req, res, next){
}
app.use(a);
app.get(a);

Types
1. Application Level middleware
var app.express()
app.use(function(req, res, next){
     console.log('hi');
     next();
});

2. Routing Level middleware
Example: 
app.use('/auth', function (req, res, next){
});

3. Inbuilt Level middleware
Program -> inactive state
Process -> active state (thread- execution sequence of process eg: save, delete, edit).
- NodeJS is single threaded programming language. Process is keyword that holds running process instance. 0-> false, 1-> true
Example:
var path = require('path);
app.use('images', express.staet(path.join __dirname, 'images'))

4. Third Part Level middleware (available in nodejs.com)
Example: Morgan (req. logger middleware for node js)

5. Error Handling Level middleware
Example:
app.use(function(err, req, res, next){
     console.log('Err is', err);
     res.json({
             status: err.status || 400,
             msg: err.message || "Wrong"
})
})

Description:
- it doesnt self invoked in http request cycle
- err handling middleware needs to be called execute
- call garne method next with argument
- next is middleware function
- next without arg calls another successive control
- next with arg le sidai error handling middle ware call garxa

#Templating Engine
- HTML doesn't bind data so we use template engine.
- Example: Pug, Handlebars, Ejs, Jade, Mustache


# JWT(Json Web Token)
- is open industry standard RFC 7519 method for representing claims securely between 2 parts. JWT allows you to decode, verify and generate
Parts:
1. headers (algorithms and token type)
2. Signature (secret key)
3. data (payload)

# Error Handling
- Garbage collection and error handling (memory usage release). memory usage handle
Example:
- Var A (locate memory), if its usage is over, we can make null value in A variable, this is called garbage.

Comments

Popular posts from this blog

NodeJS: Request and Respose Objects

# req Objects - req - req.body, req.queries, req.validationerrors - res.headers, req.users, req.file, req.assert - req.params, req.checkbody #res Objects - res.send, res.end, res.json, res.render, res.status, res.sendStatus # - .limit(4) //limit only upto 4 docs - skips(3) //skip first 3 docs - exe //query build and then execute, it is also callback function of mongoose. - sort({_id: -1}) //for decending order - populate('userId') //populating data inside the reference.

Javascript: Object to Array and Array to Object

Output: Final Array [ { mango: 1 }, { apple: 2 }, { banana: 3 }, { orange: 1 }, { watermelon: 1 }, { papaya: 1 } ] Output: Final Object { mango: 1, apple: 2, banana: 3, orange: 1, watermelon: 1, papaya: 1 }

Github Tutorial

GitHub brings together the world's largest community of developers to discover, share, and build better software. Delivered through software as a service(SAAS) business model 2008 by linus (Owner: Microsoft)  #Create New Repository in Github New Repository Add Repository Name and description Public / Private, initialize this repo with Read Me Create repository create a new repository on the command line echo "#test" >> README.md git init git add README.md git commit -m "first commit" git remote add origin https://github.com/sinuna/test.git git push -u origin master …or push an existing repository from the command line git remote add origin https://github.com/sinuna/firstRepository.git git push -u origin master …or import code from another repository You can initialize this repository with code from a Subversion, Mercurial, or TFS project. Initialize Repo $ git init Clone Repo $ git clone https://github.com...