0% found this document useful (0 votes)
14 views15 pages

Lab 11

The document provides an overview of Node.js including what it is, what it can do, how to install it, and examples of using core modules like HTTP and file system. It also demonstrates how to handle HTTP requests using Express by implementing GET, POST, PUT, and DELETE requests.

Uploaded by

mohyuddin6565
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views15 pages

Lab 11

The document provides an overview of Node.js including what it is, what it can do, how to install it, and examples of using core modules like HTTP and file system. It also demonstrates how to handle HTTP requests using Express by implementing GET, POST, PUT, and DELETE requests.

Uploaded by

mohyuddin6565
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

COMSATS University Islamabad

Lab Manual 11
“Getting Started With NodeJs”

WEB TECHNOLOGIES
Department of Computer Science

Node.js
What is Node.js?
 Node.js is an open source server environment
 Node.js is free
 Node.js runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
 Node.js uses JavaScript on the server

What Can Node.js Do?


 Node.js can generate dynamic page content
 Node.js can create, open, read, write, delete, and close files on the server
 Node.js can collect form data
 Node.js can add, delete, modify data in your database

Download and Install Node.js


Follow following link:

https://www.youtube.com/watch?v=qZQmCfkmbNA

Sample Run
1. Open Visual Code and create a “newFile.js” and past following code into it

var http = require('http');

http.createServer(function (req, res) {


res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);

Page 2
2. Now Open Command Prompt in visual code

3. Go to the Current Directory by using command cd


example you want to go to folder myfolder then type cd myFolder
4. Now execute current file by command node newFile.js
5. Go to browser and open url localhost:8080

Page 3
Explanation of Code

require() is a module.

Consider modules to be the same as JavaScript libraries.

A set of functions you want to include in your application.

var http = require('http');

Now your application has access to the HTTP module, and is able to create a server:

If anyone tries to access your computer on port 8080, they will get a "Hello World!"
message in return!

List Of Modules

Page 4
Page 5
Use Of ‘fileSystem’ Modules

Common use for the File System module:

 Read files
 Create files
 Update files
 Delete files
 Rename files

We can open HTML file using this module

Let we have myPage.html file


<!DOCTYPE html>

<html>
<head>

</head>
<body>
<h1>
my First Nodjs app
</h1>
</body>

</html>
My.js file

var http = require('http');


var fs=require('fs');
http.createServer(function (req, res) {
fs.readFile('myPage.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);

Page 6
res.end();
});
}).listen(8080);

Handling HTTP get Request

We Use EXPRESS Module for This Purpose


You can install this module by typing following command
on terminal
npm install express

Sample Code

var express= require('express');

var app = express();

app.get('/',(req,res)=>{

res.send("url with no parameter");

});

app.get('/api',(req,res)=>{

res.send(" Api");

});
Page 7
app.listen(8080,()=>{console.log("listning at 8080")});

url
localhost:8080 (output : url with no parameter)
localhost:8080 (output : Api)
Passing A value in url

http://localhost:8080/api/3
Note : data always passed in string form.

Code
app.get('/api/:id',(req,res)=>{

res.send("id = "+(req.params.id));

});

Handling HTTP POST Request

Adding A course
Code

var express= require('express');

var app = express();

Page 8
app.use(express.json()); //use to enable JASON

var courses = [
{
id:1 , name:'course1'
},
{
id:2 , name:'course2'
},
{
id:3 , name:'course3'
}

];

app.post('/api/courses',(req,res) => {

var course = {
id: courses.length+1,
name: req.body.name
};

courses.push(course);
res.send(course);

});

app.listen(8080,()=>{console.log("listning at 8080")});

NOW Send Data from end point

Go to Google Chrome and Add extension chrome postman

Page 9
You could see postman app icon

Now open it.

Page 10
Do not sign Up just click on the link at the bottom

Now make changes step by step given below

Page 11
At the bottom you will see the response from server

Handling HTTP PUT Request

Updating A course

app.put('/api/courses/:id' , (req,res)=>{

Page 12
var course = courses.find(c=> c.id === parseInt(req.params.id));
if(!course) res.status(404).send('The Course with given ID not Exist');

if(req.body.name.length < 3 ){
res.status(400).send("Invalid Name");
}
else{
course.name = req.body.name;
res.send(course);
}

});

Handling HTTP delete Request


Delete A course

app.delete('/api/courses/:id' , (req,res)=>{

Page 13
var course = courses.find(c=> c.id === parseInt(req.params.id));
if(!course) res.status(404).send('The Course with given ID not Exist');

var courseIndex = corses.indexOf(course);


courses.splice(courseIndex,1);
res.send(course);

});

Class Task
Create following API Using Get, Post, Put and Delete Requests

Let You Have an Object Named CAR with following attributes

var Car = [
{
name:'Mehran' , color:'Red' , price = 100000
},

Page 14
{
name:'Cultus' , color:'White' , price = 300000
},
{
name:'Corrola' , color:'Black' , price = 1500000
}

];

And perform following queries

1. Display price of car when is passed through url name


2. Display All Cars List
3. Display all cars having price greater than the amount passes through Url
4. Update the price of the car (name of car and updated price will be passed through url)
5. Delete a car by its name given through url
6. Insert new car data

Page 15

You might also like