
Node.JS - Express
Eueung Mulyana
http://eueung.github.io/js/express
JS CodeLabs | Attribution-ShareAlike CC BY-SA
1 / 21
Agenda
Basics
RESTful APIs
2 / 21
 Basics
3 / 21
Example #1
$nodeex-01-expressjs.js
Exampleapplisteningathttp://:::3000
varexpress=require('express');
varapp=express();
//----------------------------------
app.get('/',function(req,res){
res.send('HelloWorld!');
});
//----------------------------------
varserver=app.listen(3000,function(){
varhost=server.address().address;
varport=server.address().port;
console.log('Exampleapplisteningathttp://%s:%s',host,port);
});
 
4 / 21
The app starts a server and listens on port 3000 for
connections. The app responds with “Hello World!” for
requests to the root URL (/) or route. For every other
path, it will respond with a 404 Not Found.
The req (request) and res (response) are the exact same
objects that Node provides, so you can invoke req.pipe(),
req.on('data', callback), and anything else you would do
without Express involved.
Express vs. http Module
varhttp=require('http');
varserver=http.createServer(function(){});
server.listen(3000,function(){
console.log("Listeningonport3000");
});
varexpress=require('express');
varapp=express();
varserver=app.listen(3000,function(){
console.log('Listeningonport%d',server.address().port)
});
5 / 21
varexpress=require('express');
varapp=express();
//--------------------------------------------------
app.get('/',function(req,res){
console.log("GotaGETrequestforthehomepage");
res.send('HelloGET');})
//--------------------------------------------------
app.post('/',function(req,res){
console.log("GotaPOSTrequestforthehomepage");
res.send('HelloPOST');})
//--------------------------------------------------
app.delete('/del_user',function(req,res){
console.log("GotaDELETErequestfor/del_user");
res.send('HelloDELETE');})
//--------------------------------------------------
app.get('/list_user',function(req,res){
console.log("GotaGETrequestfor/list_user");
res.send('PageListing');})
//--------------------------------------------------
//ThisrespondsaGETrequestforabcd,abxcd,ab123cd,andsoon
app.get('/ab*cd',function(req,res){
console.log("GotaGETrequestfor/ab*cd");
res.send('PagePatternMatch');})
//--------------------------------------------------
varserver=app.listen(8081,function(){
varhost=server.address().address
varport=server.address().port
console.log("Exampleapplisteningathttp://%s:%s",host,port)
})
Example #2
$>nodeex-02.js
Exampleapplisteningathttp://:::8081
GotaGETrequestforthehomepage
GotaPOSTrequestforthehomepage
GotaGETrequestfor/list_user
GotaDELETErequestfor/del_user
GotaGETrequestfor/ab*cd
6 / 21
7 / 21
$>nodeex-03.js
Exampleapplisteningathttp://:::8081
{first_name:'Dodol',last_name:'Garut'}
varexpress=require('express');
varapp=express();
//-----------------------------------------
app.use(express.static('ex-03'));//get'/'langsung
//-----------------------------------------
app.get('/index-get',function(req,res){
res.sendFile(__dirname+"/ex-03/"+"index-get.html");});
//-----------------------------------------
app.get('/process_get',function(req,res){
response={
first_name:req.query.first_name,
last_name:req.query.last_name
};
console.log(response);
res.end(JSON.stringify(response));
});
//-----------------------------------------
varserver=app.listen(8081,function(){
varhost=server.address().address
varport=server.address().port
console.log("Exampleapplisteningathttp://%s:%s",host,port)
});
Example #3 (GET)
 
 
 
8 / 21
Example #3 (POST)
 
 
$>nodeex-03-post.js
Exampleapplisteningathttp://:::8081
{first_name:'dodolviapost',last_name:'garutjgviapost'
varexpress=require('express');
varapp=express();
varbodyParser=require('body-parser');
//Createapplication/x-www-form-urlencodedparser
varurlencodedParser=bodyParser.urlencoded({extended:false
app.use(express.static('ex-03'));
//-----------------------------------------------
app.get('/index-post',function(req,res){
res.sendFile(__dirname+"/ex-03/"+"index-post.html");
})
//-----------------------------------------------
app.post('/process_post',urlencodedParser,function(req,res
response={
first_name:req.body.first_name,
last_name:req.body.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
//-----------------------------------------------
varserver=app.listen(8081,function(){
varhost=server.address().address
varport=server.address().port
console.log("Exampleapplisteningathttp://%s:%s",host,p
})
9 / 21
index-get.html
<html><body>
<formaction="http://127.0.0.1:8081/process_get"method="GET"
FirstName:<inputtype="text"name="first_name"> <br>
LastName:<inputtype="text"name="last_name">
<inputtype="submit"value="Submit">
</form>
</body></html>
index-post.html
<html><body>
<formaction="http://127.0.0.1:8081/process_post"method="POST
FirstName:<inputtype="text"name="first_name"> <br>
LastName:<inputtype="text"name="last_name">
<inputtype="submit"value="Submit">
</form>
</body></html>
10 / 21
Example #4
File Uploads
app.post('/file_upload',upload.single('file'),function(req,res)
console.log(req.file.originalname);
console.log(req.file.path);
console.log(req.file.mimetype);
varfile=__dirname+"/ex-04/result/"+req.file.originalname;
fs.readFile(req.file.path,function(err,data){
fs.writeFile(file,data,function(err){
if(err){console.log(err);}
else{response={message:'Fileuploadedsuccessfully'
console.log(response);
res.end(JSON.stringify(response));
});
});
});
varexpress=require('express');
varapp=express();
varfs=require("fs");
varbodyParser=require('body-parser');
varmulter =require('multer');
//--------------------------
app.use(express.static('ex-04/public'));
app.use(bodyParser.urlencoded({extended:false}));
varupload=multer({dest:'ex-04/tmp/'});
//--------------------------
app.get('/index-upload',function(req,res){res.sendFile(_
//--------------------------
//...
//--------------------------
varserver=app.listen(8081,function(){
varhost=server.address().address
varport=server.address().port
console.log("Exampleapplisteningathttp://%s:%s",host,p
});
11 / 21
Example #4
$>nodeex-04.js
Exampleapplisteningathttp://:::8081
Drones.pdf
ex-04tmp0c1fd33b722f40f26cb34d35f28f72d1
application/pdf
{message:'Fileuploadedsuccessfully',
filename:'Drones.pdf'}
<html><head><title>FileUploadingForm</title></head>
<body>
<h3>FileUpload:</h3>
Selectafiletoupload:<br/>
<formaction="http://127.0.0.1:8081/file_upload"method="POST"
enctype="multipart/form-data">
<inputtype="file"name="file"size="50"/>
<br/>
<inputtype="submit"value="UploadFile"/>
</form>
</body></html>
 
12 / 21
Example #5
cookie-parser
$>nodeex-05.js
Exampleapplisteningathttp://:::8081
Cookies: {Cho:'Kim',Greet:'Hello'}
Cookies: {}
$>curlhttp://localhost:8081--cookie"Cho=Kim;Greet=Hello"
RequestReceived!
$>curlhttp://localhost:8081
RequestReceived!
varexpress =require('express');
varcookieParser=require('cookie-parser');
//----------------------------------------
varapp=express();
app.use(cookieParser());
//----------------------------------------
app.get('/',function(req,res){
console.log("Cookies:",req.cookies);
res.send('RequestReceived!');
});
//----------------------------------------
varserver=app.listen(8081,function(){
varhost=server.address().address
varport=server.address().port
console.log("Exampleapplisteningathttp://%s:%s",host,p
});
13 / 21
 RESTful APIs
14 / 21
varexpress=require('express');
varapp=express();
varfs=require("fs");
//------------------
//caseinsensitive
app.get('/listUsers',function(req,res){
fs.readFile(__dirname+"/"+"ex-06-users.json",'utf8'
console.log(data);
res.end(data);
});
});
//------------------
varserver=app.listen(8081,function(){
varhost=server.address().address
varport=server.address().port
console.log("Exampleapplisteningathttp://%s:%s",host,port)
});
Example #6
Using Flat JSON File
GET /listusers
 
15 / 21
Example #6
POST /adduser
varserver=app.listen(8081,function(){
varhost=server.address().address
varport=server.address().port
console.log("Exampleapplisteningathttp://%s:%s",host,port)
});
varexpress=require('express');
varapp=express();
varfs=require("fs");
varbodyParser=require('body-parser');
//------------------
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
//------------------
functionsaveJson(filename,filecontent){
fs.writeFile(filename,filecontent, function(err){
if(err){returnconsole.error(err);}
});
}
//------------------
app.post('/addUser',function(req,res){
fs.readFile(__dirname+"/"+"ex-06-users.json",'utf8'
data=JSON.parse(data);//console.log(req.body);
data["user"+req.body.id]={}
data["user"+req.body.id].name=req.body.name
data["user"+req.body.id].password=req.body.password
data["user"+req.body.id].profession=req.body.profes
data["user"+req.body.id].id=+req.body.id
console.log(data);
res.end(JSON.stringify(data));
saveJson(__dirname+"/"+"ex-06-users.json",JSON.st
});
});
16 / 21
17 / 21
varexpress=require('express');
varapp=express();
varfs=require("fs");
//---------------------
app.get('/:id',function(req,res){
fs.readFile(__dirname+"/"+"ex-06-users.json",'utf8'
data=JSON.parse(data);
varuser=data["user"+req.params.id]
console.log(user);
res.end(JSON.stringify(user));
});
});
//---------------------
varserver=app.listen(8081,function(){
varhost=server.address().address
varport=server.address().port
console.log("Exampleapplisteningathttp://%s:%s",host,port)
});
Example #6
GET /:id
 
18 / 21
Example #6
DELETE /deleteuser
 
varexpress=require('express');
varapp=express();
varfs=require("fs");
varbodyParser=require('body-parser');
//------------------
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
//------------------
functionsaveJson(filename,filecontent){
fs.writeFile(filename,filecontent, function(err){
if(err){returnconsole.error(err);}
});
}
//---------------------
app.delete('/deleteUser',function(req,res){
fs.readFile(__dirname+"/"+"ex-06-users.json",'utf8'
data=JSON.parse(data);
deletedata["user"+req.body.id];
console.log(data);
res.end(JSON.stringify(data));
saveJson(__dirname+"/"+"ex-06-users.json",JSON.st
});
});
//---------------------
varserver=app.listen(8081,function(){
varhost=server.address().address
varport=server.address().port
console.log("Exampleapplisteningathttp://%s:%s",host,p
});
19 / 21
References
1. Express Example
2. Node.js Express Framework
3. Express to Hapi.js
4. expressjs/multer
5. expressjs/body-parser
6. expressjs/cookie-parser
7. Node.js RESTful API
Other Readings
1. JavaScript and Cookies
2. JavaScript Cookies
20 / 21

END
Eueung Mulyana
http://eueung.github.io/js/express
JS CodeLabs | Attribution-ShareAlike CC BY-SA
21 / 21

Introduction to Node.JS Express