Saturday, August 8, 2020

Nodejs Lab setup and sample express app

 Install nodejs on your machine using link

After that, you can create a nodejs project on a new folder by running below command and provide the details.


>npm init --> to create a new node project.

This creates a package.json file with all the details and prerequisites.


Express is a node runtime library having helpers to make dealing with HTTP traffic easier.

Express looks at the request and decides what chunk of code will "handle" or respond to the request.


Now, to create an express app, we need to include the module first.

In our project folder, run below command.

>npm install --save express

An entry also will be added to package.json file.

Add files will be downloaded to nodes_modules folder.



Editor add-on to auto-format your JS

https://github.com/prettier/prettier

Using some editor, mostly atom, create file index.js.


//instead of es2015 we use commentjs modules will be supported by node, so require is used instead of import.Reactjs will use import.
const express = require('express');
const app = express(); //generates a new express app
app.get('/',(req,res)=> {
  res.send({hi: 'there'});
});
app.listen(5000);


>node index.js

on browser http://localhost:5000


Above code, 

"app" represents Express app tp register this route handler with.

"get" watch for incoming requests with this method.

"/" watch for requests trying to access '/'.

res.send() parts send some json back to whoever made this request.


Other methods express has access to:


app.get --> Get info, post--> send info, put --> update all the properties of something.

delete --> delete something. patch --> update one or more properties of something.


app.listen() --> express telling node to listen to 5000 port for incoming traffic and that will be routed to express.


No comments:

Post a Comment