Step 1: Create
package.json file.
Create a folder HelloWorld.
Open terminal, go inside 'HelloWorld directory and
execute the command 'npm init -y'. It creates a default package.json file.
$npm init -y Wrote to C:\Users\krishna\HelloWorld\package.json: { "name": "HelloWorld", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }
Step 2: Install
express dependency by executing the below command.
npm install --save express
You should execute the above command from the directory,
where your package.json file located. This command downloads the express module
from Internet and update the package.json file with express dependency.
After executing the command, package.json looks like
below.
{ "name": "HelloWorld", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "express": "^4.16.4" } }
After executing the above command, you can observe below
two changes.
a.
There is a file package-lock.json file is
created, it contain all the dependencies required by express
b.
node_modules folder is created. All the
downloaded dependencies are placed in this folder.
Step 2: Create
index.js file in the same place where your package.json located.
index.js
//Load express module const express = require('express'); //Put new Express application inside app variable const app = express(); const port = 8080; //When user hits the home page, then the message prints in browser. app.get('/', (req, res) => res.send('Welcome to Node.js Programming')) app.get('/time', (req, res) => res.send(new Date().toString())) app.get('/welcome', (req, res) => { var userName = req.query.name res.send("Hello Mr."+ userName) }) app.get('/welcome/:userName', (req, res) => { res.send("Hello Mr."+ req.params.userName) }) // Start the express application on port 8080 and print server start message to console. app.listen(port, () => console.log(`Application started listening on port ${port}!`));
app.get('/', (req,
res) => res.send('Welcome to Node.js Programming'))
Above snippet handle the requests to home page.
app.get('/time',
(req, res) => res.send(new Date().toString()))
Above snippet handle the request uri /time
app.get('/welcome',
(req, res) => {
var userName = req.query.name
res.send("Hello Mr."+
userName)
})
Above snippet handle the request uri /welcome
app.get('/welcome/:userName',
(req, res) => {
res.send("Hello Mr."+
req.params.userName)
})
Above snippet handle the request uri /welcome/{SOME_NAME}
Open terminal and execute the command ‘node
index.js’ to start the application.
No comments:
Post a Comment