SlideShare a Scribd company logo
CS142 Lecture Notes - Express.js
ExpressJS
Mendel Rosenblum
CS142 Lecture Notes - Express.js
Express.js - A web framework for Node.js
Fast, unopinionated, minimalist web framework
Relatively thin layer on top of the base Node.js functionality
What does a web server implementor need?
● Speak HTTP: Accept TCP connections, process HTTP request, send HTTP replies
Node's HTTP module does this
● Routing: Map URLs to the web server function for that URL
Need to support a routing table (like React Router)
● Middleware support: Allow request processing layers to be added in
Make it easy to add custom support for sessions, cookies, security, compression, etc.
CS142 Lecture Notes - Express.js
var express = require('express');
var expressApp = express(); // module uses factory pattern
// expressApp object has methods for:
○ Routing HTTP requests
○ Rendering HTML (e.g. run a preprocessor like Jade templating engine)
○ Configuring middleware and preprocessors
expressApp.get('/', function (httpRequest, httpResponse) {
httpResponse.send('hello world');
});
expressApp.listen(3000); // default address localhost use port 3000
CS142 Lecture Notes - Express.js
Express routing
● By HTTP method:
expressApp.get(urlPath, requestProcessFunction);
expressApp.post(urlPath, requestProcessFunction);
expressApp.put(urlPath, requestProcessFunction);
expressApp.delete(urlPath, requestProcessFunction);
expressApp.all(urlPath, requestProcessFunction);
● Many others less frequently used methods
● urlPath can contain parameters like React Router (e.g. '/user/:user_id')
CS142 Lecture Notes - Express.js
httpRequest object
expressApp.get('/user/:user_id', function (httpRequest, httpResponse) …
● Object with large number of properties
Middleware (like JSON body parser, session manager, etc.) can add properties
request.params - Object containing url route params (e.g. user_id)
request.query - Object containing query params (e.g. &foo=9 ⇒ {foo: '9'})
request.body - Object containing the parsed body
request.get(field) - Return the value of the specified HTTP header field
CS142 Lecture Notes - Express.js
httpResponse object
expressApp.get('/user/:user_id', function (httpRequest, httpResponse) …
● Object with a number of methods for setting HTTP response fields
response.write(content) - Build up the response body with content
response.status(code) - Set the HTTP status code of the reply
response.set(prop, value) - Set the response header property to value
response.end() - End the request by responding to it
response.end(msg) - End the request by responding with msg
response.send(content) - Do a write() and end()
● Methods return the response object so they stack (i.e. return this;)
response.status(code).write(content1).write(content2).end();
CS142 Lecture Notes - Express.js
Middleware
● Give other software the ability to interpose on requests
expressApp.all(urlPath, function (request, response, next) {
// Do whatever processing on request (or setting response)
next(); // pass control to the next handler
});
● Interposing on all request using the route mechanism
expressApp.use(function (request, response, next) {...});
● Examples:
○ Check to see if user is logged in, otherwise send error response and don't call next()
○ Parse the request body as JSON and attached the object to request.body and call next()
○ Session and cookie management, compression, encryption, etc.
CS142 Lecture Notes - Express.js
ExpressJS Example: webServer.js from Project #4
var express = require('express');
var app = express(); // Creating an Express "App"
app.use(express.static(__dirname)); // Adding middleware
app.get('/', function (request, response) { // A simple request handler
response.send('Simple web server of files from ' + __dirname);
});
app.listen(3000, function () { // Start Express on the requests
console.log('Listening at http://localhost:3000 exporting the directory ' +
__dirname);
});
CS142 Lecture Notes - Express.js
ExpressJS Example: webServer.js from Project #5
app.get('/user/list', function (request, response) {
response.status(200).send(cs142models.userListModel());
return;
});
app.get('/user/:id', function (request, response) {
var id = request.params.id;
var user = cs142models.userModel(id);
if (user === null) {
console.log('User with _id:' + id + ' not found.');
response.status(400).send('Not found');
return;
}
response.status(200).send(user);
return;
});
CS142 Lecture Notes - Express.js
A Simple Model Fetcher - Fetch from a JSON file
expressApp.get("/object/:objid", function (request, response) {
var dbFile = "DB" + request.params.objid;
fs.readFile(dbFile, function (error, contents) {
if (error) {
response.status(500).send(error.message);
} else {
var obj = JSON.parse(contents); // JSON.parse accepts Buffer types
obj.date = new Date();
response.set('Content-Type', 'application/json'); // Same: response.json(obj);
response.status(200).send(JSON.stringify(obj));
}
}); Note: Make sure you always call end() or send()
}
CS142 Lecture Notes - Express.js
A Simple Model Fetcher - Fetch from a JSON file
expressApp.get("/object/:objid", function (request, response) {
var dbFile = "DB" + request.params.objid;
fs.readFile(dbFile, function (error, contents) {
if (error) {
response.status(500).send(error.message);
} else {
var obj = JSON.parse(contents); // JSON.parse accepts Buffer types
obj.date = new Date();
response.json(obj);
}
});
}
CS142 Lecture Notes - Express.js
Fetching multiple models - Comments of objects
app.get("/commentsOf/:objid", function (request, response) {
var comments = [];
fs.readFile("DB" + request.params.objid, function (error, contents) {
var obj = JSON.parse(contents);
async.each(obj.comments, fetchComments, allDone);
});
function fetchComments(commentFile, callback) {
fs.readFile("DB"+ commentFile, function (error, contents) {
if (!error) comments.push(JSON.parse(contents));
callback(error);
});
}
function allDone(error) {
if (error) responses.status(500).send(error.message); else response.json(comments);
}
});

More Related Content

Similar to Express.pdf

Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NET
Gianluca Carucci
 
Intro to Node
Intro to NodeIntro to Node
Intro to Node
Aaron Stannard
 
Express js
Express jsExpress js
Express js
Manav Prasad
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
davidchubbs
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
Jeetendra singh
 
Nodejs first class
Nodejs first classNodejs first class
Nodejs first class
Fin Chen
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
Ben Lin
 
NodeJSnodesforfreeinmyworldgipsnndnnd.pdf
NodeJSnodesforfreeinmyworldgipsnndnnd.pdfNodeJSnodesforfreeinmyworldgipsnndnnd.pdf
NodeJSnodesforfreeinmyworldgipsnndnnd.pdf
VivekSonawane45
 
Express JS-Routingmethod.pdf
Express JS-Routingmethod.pdfExpress JS-Routingmethod.pdf
Express JS-Routingmethod.pdf
Bareen Shaikh
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
Sam Brannen
 
05 status-codes
05 status-codes05 status-codes
05 status-codes
snopteck
 
Local SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLocal SQLite Database with Node for beginners
Local SQLite Database with Node for beginners
Laurence Svekis ✔
 
Slickdemo
SlickdemoSlickdemo
Slickdemo
Knoldus Inc.
 
NodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdf
ArthyR3
 
Introducing Node.js in an Oracle technology environment (including hands-on)
Introducing Node.js in an Oracle technology environment (including hands-on)Introducing Node.js in an Oracle technology environment (including hands-on)
Introducing Node.js in an Oracle technology environment (including hands-on)
Lucas Jellema
 
03 form-data
03 form-data03 form-data
03 form-data
snopteck
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Somkiat Puisungnoen
 
Extending the WordPress REST API - Josh Pollock
Extending the WordPress REST API - Josh PollockExtending the WordPress REST API - Josh Pollock
Extending the WordPress REST API - Josh Pollock
Caldera Labs
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express js
Ahmed Assaf
 
Using the new WordPress REST API
Using the new WordPress REST APIUsing the new WordPress REST API
Using the new WordPress REST API
Caldera Labs
 

Similar to Express.pdf (20)

Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NET
 
Intro to Node
Intro to NodeIntro to Node
Intro to Node
 
Express js
Express jsExpress js
Express js
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
Nodejs first class
Nodejs first classNodejs first class
Nodejs first class
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
NodeJSnodesforfreeinmyworldgipsnndnnd.pdf
NodeJSnodesforfreeinmyworldgipsnndnnd.pdfNodeJSnodesforfreeinmyworldgipsnndnnd.pdf
NodeJSnodesforfreeinmyworldgipsnndnnd.pdf
 
Express JS-Routingmethod.pdf
Express JS-Routingmethod.pdfExpress JS-Routingmethod.pdf
Express JS-Routingmethod.pdf
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
05 status-codes
05 status-codes05 status-codes
05 status-codes
 
Local SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLocal SQLite Database with Node for beginners
Local SQLite Database with Node for beginners
 
Slickdemo
SlickdemoSlickdemo
Slickdemo
 
NodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdf
 
Introducing Node.js in an Oracle technology environment (including hands-on)
Introducing Node.js in an Oracle technology environment (including hands-on)Introducing Node.js in an Oracle technology environment (including hands-on)
Introducing Node.js in an Oracle technology environment (including hands-on)
 
03 form-data
03 form-data03 form-data
03 form-data
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Extending the WordPress REST API - Josh Pollock
Extending the WordPress REST API - Josh PollockExtending the WordPress REST API - Josh Pollock
Extending the WordPress REST API - Josh Pollock
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express js
 
Using the new WordPress REST API
Using the new WordPress REST APIUsing the new WordPress REST API
Using the new WordPress REST API
 

More from stephanedjeukam1

HTTP.pdf
HTTP.pdfHTTP.pdf
Database.pdf
Database.pdfDatabase.pdf
Database.pdf
stephanedjeukam1
 
HTML.pdf
HTML.pdfHTML.pdf
CodeInjection.pdf
CodeInjection.pdfCodeInjection.pdf
CodeInjection.pdf
stephanedjeukam1
 
Input.pdf
Input.pdfInput.pdf
Input.pdf
stephanedjeukam1
 
FrontEnd.pdf
FrontEnd.pdfFrontEnd.pdf
FrontEnd.pdf
stephanedjeukam1
 
DOM.pdf
DOM.pdfDOM.pdf
CSS.pdf
CSS.pdfCSS.pdf
DOSAttacks.pdf
DOSAttacks.pdfDOSAttacks.pdf
DOSAttacks.pdf
stephanedjeukam1
 
0000 Syllabus.pdf
0000  Syllabus.pdf0000  Syllabus.pdf
0000 Syllabus.pdf
stephanedjeukam1
 
Events.pdf
Events.pdfEvents.pdf
Events.pdf
stephanedjeukam1
 

More from stephanedjeukam1 (11)

HTTP.pdf
HTTP.pdfHTTP.pdf
HTTP.pdf
 
Database.pdf
Database.pdfDatabase.pdf
Database.pdf
 
HTML.pdf
HTML.pdfHTML.pdf
HTML.pdf
 
CodeInjection.pdf
CodeInjection.pdfCodeInjection.pdf
CodeInjection.pdf
 
Input.pdf
Input.pdfInput.pdf
Input.pdf
 
FrontEnd.pdf
FrontEnd.pdfFrontEnd.pdf
FrontEnd.pdf
 
DOM.pdf
DOM.pdfDOM.pdf
DOM.pdf
 
CSS.pdf
CSS.pdfCSS.pdf
CSS.pdf
 
DOSAttacks.pdf
DOSAttacks.pdfDOSAttacks.pdf
DOSAttacks.pdf
 
0000 Syllabus.pdf
0000  Syllabus.pdf0000  Syllabus.pdf
0000 Syllabus.pdf
 
Events.pdf
Events.pdfEvents.pdf
Events.pdf
 

Recently uploaded

怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
rtunex8r
 
一比一原版(USYD毕业证)悉尼大学毕业证如何办理
一比一原版(USYD毕业证)悉尼大学毕业证如何办理一比一原版(USYD毕业证)悉尼大学毕业证如何办理
一比一原版(USYD毕业证)悉尼大学毕业证如何办理
k4ncd0z
 
Securing BGP: Operational Strategies and Best Practices for Network Defenders...
Securing BGP: Operational Strategies and Best Practices for Network Defenders...Securing BGP: Operational Strategies and Best Practices for Network Defenders...
Securing BGP: Operational Strategies and Best Practices for Network Defenders...
APNIC
 
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
thezot
 
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
APNIC
 
Bengaluru Dreamin' 24 - Personal Branding
Bengaluru Dreamin' 24 - Personal BrandingBengaluru Dreamin' 24 - Personal Branding
Bengaluru Dreamin' 24 - Personal Branding
Tarandeep Singh
 
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
3a0sd7z3
 
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
xjq03c34
 
Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?
Paul Walk
 
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
3a0sd7z3
 
HijackLoader Evolution: Interactive Process Hollowing
HijackLoader Evolution: Interactive Process HollowingHijackLoader Evolution: Interactive Process Hollowing
HijackLoader Evolution: Interactive Process Hollowing
Donato Onofri
 
Discover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to IndiaDiscover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to India
davidjhones387
 

Recently uploaded (12)

怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
 
一比一原版(USYD毕业证)悉尼大学毕业证如何办理
一比一原版(USYD毕业证)悉尼大学毕业证如何办理一比一原版(USYD毕业证)悉尼大学毕业证如何办理
一比一原版(USYD毕业证)悉尼大学毕业证如何办理
 
Securing BGP: Operational Strategies and Best Practices for Network Defenders...
Securing BGP: Operational Strategies and Best Practices for Network Defenders...Securing BGP: Operational Strategies and Best Practices for Network Defenders...
Securing BGP: Operational Strategies and Best Practices for Network Defenders...
 
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
 
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
 
Bengaluru Dreamin' 24 - Personal Branding
Bengaluru Dreamin' 24 - Personal BrandingBengaluru Dreamin' 24 - Personal Branding
Bengaluru Dreamin' 24 - Personal Branding
 
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
 
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
 
Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?
 
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
 
HijackLoader Evolution: Interactive Process Hollowing
HijackLoader Evolution: Interactive Process HollowingHijackLoader Evolution: Interactive Process Hollowing
HijackLoader Evolution: Interactive Process Hollowing
 
Discover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to IndiaDiscover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to India
 

Express.pdf

  • 1. CS142 Lecture Notes - Express.js ExpressJS Mendel Rosenblum
  • 2. CS142 Lecture Notes - Express.js Express.js - A web framework for Node.js Fast, unopinionated, minimalist web framework Relatively thin layer on top of the base Node.js functionality What does a web server implementor need? ● Speak HTTP: Accept TCP connections, process HTTP request, send HTTP replies Node's HTTP module does this ● Routing: Map URLs to the web server function for that URL Need to support a routing table (like React Router) ● Middleware support: Allow request processing layers to be added in Make it easy to add custom support for sessions, cookies, security, compression, etc.
  • 3. CS142 Lecture Notes - Express.js var express = require('express'); var expressApp = express(); // module uses factory pattern // expressApp object has methods for: ○ Routing HTTP requests ○ Rendering HTML (e.g. run a preprocessor like Jade templating engine) ○ Configuring middleware and preprocessors expressApp.get('/', function (httpRequest, httpResponse) { httpResponse.send('hello world'); }); expressApp.listen(3000); // default address localhost use port 3000
  • 4. CS142 Lecture Notes - Express.js Express routing ● By HTTP method: expressApp.get(urlPath, requestProcessFunction); expressApp.post(urlPath, requestProcessFunction); expressApp.put(urlPath, requestProcessFunction); expressApp.delete(urlPath, requestProcessFunction); expressApp.all(urlPath, requestProcessFunction); ● Many others less frequently used methods ● urlPath can contain parameters like React Router (e.g. '/user/:user_id')
  • 5. CS142 Lecture Notes - Express.js httpRequest object expressApp.get('/user/:user_id', function (httpRequest, httpResponse) … ● Object with large number of properties Middleware (like JSON body parser, session manager, etc.) can add properties request.params - Object containing url route params (e.g. user_id) request.query - Object containing query params (e.g. &foo=9 ⇒ {foo: '9'}) request.body - Object containing the parsed body request.get(field) - Return the value of the specified HTTP header field
  • 6. CS142 Lecture Notes - Express.js httpResponse object expressApp.get('/user/:user_id', function (httpRequest, httpResponse) … ● Object with a number of methods for setting HTTP response fields response.write(content) - Build up the response body with content response.status(code) - Set the HTTP status code of the reply response.set(prop, value) - Set the response header property to value response.end() - End the request by responding to it response.end(msg) - End the request by responding with msg response.send(content) - Do a write() and end() ● Methods return the response object so they stack (i.e. return this;) response.status(code).write(content1).write(content2).end();
  • 7. CS142 Lecture Notes - Express.js Middleware ● Give other software the ability to interpose on requests expressApp.all(urlPath, function (request, response, next) { // Do whatever processing on request (or setting response) next(); // pass control to the next handler }); ● Interposing on all request using the route mechanism expressApp.use(function (request, response, next) {...}); ● Examples: ○ Check to see if user is logged in, otherwise send error response and don't call next() ○ Parse the request body as JSON and attached the object to request.body and call next() ○ Session and cookie management, compression, encryption, etc.
  • 8. CS142 Lecture Notes - Express.js ExpressJS Example: webServer.js from Project #4 var express = require('express'); var app = express(); // Creating an Express "App" app.use(express.static(__dirname)); // Adding middleware app.get('/', function (request, response) { // A simple request handler response.send('Simple web server of files from ' + __dirname); }); app.listen(3000, function () { // Start Express on the requests console.log('Listening at http://localhost:3000 exporting the directory ' + __dirname); });
  • 9. CS142 Lecture Notes - Express.js ExpressJS Example: webServer.js from Project #5 app.get('/user/list', function (request, response) { response.status(200).send(cs142models.userListModel()); return; }); app.get('/user/:id', function (request, response) { var id = request.params.id; var user = cs142models.userModel(id); if (user === null) { console.log('User with _id:' + id + ' not found.'); response.status(400).send('Not found'); return; } response.status(200).send(user); return; });
  • 10. CS142 Lecture Notes - Express.js A Simple Model Fetcher - Fetch from a JSON file expressApp.get("/object/:objid", function (request, response) { var dbFile = "DB" + request.params.objid; fs.readFile(dbFile, function (error, contents) { if (error) { response.status(500).send(error.message); } else { var obj = JSON.parse(contents); // JSON.parse accepts Buffer types obj.date = new Date(); response.set('Content-Type', 'application/json'); // Same: response.json(obj); response.status(200).send(JSON.stringify(obj)); } }); Note: Make sure you always call end() or send() }
  • 11. CS142 Lecture Notes - Express.js A Simple Model Fetcher - Fetch from a JSON file expressApp.get("/object/:objid", function (request, response) { var dbFile = "DB" + request.params.objid; fs.readFile(dbFile, function (error, contents) { if (error) { response.status(500).send(error.message); } else { var obj = JSON.parse(contents); // JSON.parse accepts Buffer types obj.date = new Date(); response.json(obj); } }); }
  • 12. CS142 Lecture Notes - Express.js Fetching multiple models - Comments of objects app.get("/commentsOf/:objid", function (request, response) { var comments = []; fs.readFile("DB" + request.params.objid, function (error, contents) { var obj = JSON.parse(contents); async.each(obj.comments, fetchComments, allDone); }); function fetchComments(commentFile, callback) { fs.readFile("DB"+ commentFile, function (error, contents) { if (!error) comments.push(JSON.parse(contents)); callback(error); }); } function allDone(error) { if (error) responses.status(500).send(error.message); else response.json(comments); } });