Lab 11
Lab 11
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
https://www.youtube.com/watch?v=qZQmCfkmbNA
Sample Run
1. Open Visual Code and create a “newFile.js” and past following code into it
Page 2
2. Now Open Command Prompt in visual code
Page 3
Explanation of Code
require() is a module.
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
Read files
Create files
Update files
Delete files
Rename files
<html>
<head>
</head>
<body>
<h1>
my First Nodjs app
</h1>
</body>
</html>
My.js file
Page 6
res.end();
});
}).listen(8080);
Sample Code
app.get('/',(req,res)=>{
});
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));
});
Adding A course
Code
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")});
Page 9
You could see postman app icon
Page 10
Do not sign Up just click on the link at the bottom
Page 11
At the bottom you will see the response from server
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);
}
});
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');
});
Class Task
Create following API Using Get, Post, Put and Delete Requests
var Car = [
{
name:'Mehran' , color:'Red' , price = 100000
},
Page 14
{
name:'Cultus' , color:'White' , price = 300000
},
{
name:'Corrola' , color:'Black' , price = 1500000
}
];
Page 15