SlideShare una empresa de Scribd logo
1 de 34
Descargar para leer sin conexión
express        Web
     weibo.com/mengxy

      www.imeigu.com
•
 •
 •
•
    •   Web

    •
    •
    •
    •
•
    •   Web

    •   HTML
node.js   Web
Node HTTP

•      cookie parser

•      session

•
•
Express

• Express by TJ Holowaychuk is an extremely
  popular web framework. It’s fast, simple, and
  easy to learn, and even better — it’s actively
  maintained
       ——Alex Young from dailyjs.com
demo
• git clone https://github.com/visionmedia/
  express.git
• npm install express

• node bin/express /tmp/foo && cd /tmp/foo
• npm install -d
var express = require('express');
var app = express.createServer();

app.configure(function(){
  app.use(express.bodyParser());
  app.use(express.cookieParser());
  app.use(express.session({ secret: 'your secret
here' }));
  app.use(app.router);
});

app.get('/', function(req, res){
  res.render('Hello world');
});

app.listen(3000);
Routes
function loadUser(req, res, next) {
  var user = users[req.params.id];
  if (user) {
    req.user = user;
    next();
  } else {
    next(new Error('Failed to load user ' +
req.params.id));
  }
}
app.get('/user/:id', loadUser, function(req, res){
  res.send('Viewing user ' + req.user.name);
});
Cookie & Session
function loadUser(req, res, next) {
  if (req.session.user) {
    return req.session.user;
  }
  var user = users[req.params.id];
  if (user) {
    req.session.user = req.user = user;
    next();
  } else {
    next(new Error('Failed to load user ' +
req.params.id));
  }
}
Do HTTP request


•     node http

•
request


• git clone https://github.com/mikeal/
  request.git
• npm install request
var request = require('request');
  request(
     {uri:'http://www.google.com'},
     function (error, response, body) {
     if (!error && response.statusCode == 200) {
       sys.puts(body) // Print the google web
page.
     }
  })
Template Engines

• Haml
• Jade
• EJS
• CoffeeKup
•
Mustache

• Logic-less templates
•

•
Stache
 • Stache is mustache.js for your node
    express apps


app.set('view engine', 'mustache')
app.register(".mustache", require('stache'));
app.get('/', function (req, res) {
  res.render("index", {
    locals: {
       title: "Title content",
       body: "Page content"
    },
    partials: {
       heading: '<title>{{title}}</title>'
    }
  });
});

<!-- index.mustache -->
<html>
<head> {{>heading}} </head>
<body> {{{body}}} </body>
</html>
app.get('/', function (req, res) {
  res.render("index", {
    locals: {
       title: "Title content",
       body: "Page content"
    },
    partials: {
       heading: '<title>{{title}}</title>'
    }
  });
});                       <html>
                            <head>
<!-- index.mustache -->     <title>Title content</title>
<html>                      </head>
<head> {{>heading}} </head> <body> Page content </body>
<body> {{{body}}} </body>   </html>
</html>
BUG
BUG



NodeJS
BUG



NodeJS
node
       node
node
                        node


1.   try{…} catch(error){…}
node
                             node


1.      try{…} catch(error){…}

2. process.on('uncaughtException', function
   (err) {//doSomething}
app.get("/err", function(req, res, next){
   fs.readFile('file', function(err, data){
      if (err) {throw err;}
   });
})
app.get("/err", function(req, res, next){
   fs.readFile('file', function(err, data){
      if (err) {next(err);}
   });
})
app.get("/err", function(req, res, next){
   fs.readFile('file', function(err, data){
      if (err) {next(err);}
   });
})
app.error(function(err, req, res){
    console.err(err.stack);
    res.render("500.html", {
      locals: {
         page_title: '500_      _i   '
      },
      status: 500
    });
  });
express                     tips
•                            try{}catch(e){}

•     routes callback     error       throw
                 error next()      express


•   uncaughtException         node

      endless world
One more tool
Forever

•
• Github: https://github.com/indexzero/
  forever
• npm install forever
• forever start app.js
Thank You!
PS: We Are Hiring!


             weibo.com/mengxy
           mengxy1987@gmail.com

Más contenido relacionado

La actualidad más candente

Hash Signaling Made Easy
Hash Signaling Made EasyHash Signaling Made Easy
Hash Signaling Made Easy
davidgouldin
 
Ring: Web Apps in Idiomatic Clojure
Ring: Web Apps in Idiomatic ClojureRing: Web Apps in Idiomatic Clojure
Ring: Web Apps in Idiomatic Clojure
Mark McGranaghan
 
YAPC::Asia 2010 Twitter解析サービス
YAPC::Asia 2010 Twitter解析サービスYAPC::Asia 2010 Twitter解析サービス
YAPC::Asia 2010 Twitter解析サービス
Yusuke Wada
 
Mojolicious, real-time web framework
Mojolicious, real-time web frameworkMojolicious, real-time web framework
Mojolicious, real-time web framework
taggg
 

La actualidad más candente (20)

Express JS
Express JSExpress JS
Express JS
 
Express JS
Express JSExpress JS
Express JS
 
Hash Signaling Made Easy
Hash Signaling Made EasyHash Signaling Made Easy
Hash Signaling Made Easy
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JS
 
Express Presentation
Express PresentationExpress Presentation
Express Presentation
 
Node.js Express Framework
Node.js Express FrameworkNode.js Express Framework
Node.js Express Framework
 
Ufo Ship for AWS ECS
Ufo Ship for AWS ECSUfo Ship for AWS ECS
Ufo Ship for AWS ECS
 
Ring: Web Apps in Idiomatic Clojure
Ring: Web Apps in Idiomatic ClojureRing: Web Apps in Idiomatic Clojure
Ring: Web Apps in Idiomatic Clojure
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.
 
Nodejs.meetup
Nodejs.meetupNodejs.meetup
Nodejs.meetup
 
YAPC::Asia 2010 Twitter解析サービス
YAPC::Asia 2010 Twitter解析サービスYAPC::Asia 2010 Twitter解析サービス
YAPC::Asia 2010 Twitter解析サービス
 
WorkFlow: An Inquiry Into Productivity by Timothy Bolton
WorkFlow:  An Inquiry Into Productivity by Timothy BoltonWorkFlow:  An Inquiry Into Productivity by Timothy Bolton
WorkFlow: An Inquiry Into Productivity by Timothy Bolton
 
Getting up and running with Zend Framework
Getting up and running with Zend FrameworkGetting up and running with Zend Framework
Getting up and running with Zend Framework
 
Getting up & running with zend framework
Getting up & running with zend frameworkGetting up & running with zend framework
Getting up & running with zend framework
 
jQuery Foot-Gun Features
jQuery Foot-Gun FeaturesjQuery Foot-Gun Features
jQuery Foot-Gun Features
 
Persistent mobile JavaScript
Persistent mobile JavaScriptPersistent mobile JavaScript
Persistent mobile JavaScript
 
Introduction to Node.JS Express
Introduction to Node.JS ExpressIntroduction to Node.JS Express
Introduction to Node.JS Express
 
Mojolicious, real-time web framework
Mojolicious, real-time web frameworkMojolicious, real-time web framework
Mojolicious, real-time web framework
 
Mojolicious on Steroids
Mojolicious on SteroidsMojolicious on Steroids
Mojolicious on Steroids
 
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
 

Destacado (8)

Code for sust_homes
Code for sust_homesCode for sust_homes
Code for sust_homes
 
TGEG Biosphere
TGEG BiosphereTGEG Biosphere
TGEG Biosphere
 
Field pre k 2010review
Field pre k 2010reviewField pre k 2010review
Field pre k 2010review
 
Un dia a l'escola 2
Un dia a l'escola 2Un dia a l'escola 2
Un dia a l'escola 2
 
Science and Engineering Resources: Physics and Astronomy
Science and Engineering Resources: Physics and AstronomyScience and Engineering Resources: Physics and Astronomy
Science and Engineering Resources: Physics and Astronomy
 
Vh sto dvd4ug
Vh sto dvd4ugVh sto dvd4ug
Vh sto dvd4ug
 
Setmana cultural 2010
Setmana cultural 2010Setmana cultural 2010
Setmana cultural 2010
 
Case workshop sep06_lyd2
Case workshop sep06_lyd2Case workshop sep06_lyd2
Case workshop sep06_lyd2
 

Similar a Build web application by express

node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascript
Eldar Djafarov
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
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
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
Alex Su
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
.toster
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
WalaSidhom1
 

Similar a Build web application by express (20)

node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascript
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
 
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
 
Nodejs first class
Nodejs first classNodejs first class
Nodejs first class
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
NodeJs
NodeJsNodeJs
NodeJs
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
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
 
Having Fun with Play
Having Fun with PlayHaving Fun with Play
Having Fun with Play
 
Developing web-apps like it's 2013
Developing web-apps like it's 2013Developing web-apps like it's 2013
Developing web-apps like it's 2013
 
Going crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPGoing crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHP
 
NodeJS
NodeJSNodeJS
NodeJS
 
Cross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App EngineCross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App Engine
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.js
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
 
Building a real life application in node js
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node js
 

Último

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Último (20)

Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 

Build web application by express

  • 1. express Web weibo.com/mengxy www.imeigu.com
  • 3. • Web • • • •
  • 4. • Web • HTML
  • 5.
  • 6. node.js Web
  • 7. Node HTTP • cookie parser • session • •
  • 8. Express • Express by TJ Holowaychuk is an extremely popular web framework. It’s fast, simple, and easy to learn, and even better — it’s actively maintained ——Alex Young from dailyjs.com
  • 9. demo • git clone https://github.com/visionmedia/ express.git • npm install express • node bin/express /tmp/foo && cd /tmp/foo • npm install -d
  • 10. var express = require('express'); var app = express.createServer(); app.configure(function(){ app.use(express.bodyParser()); app.use(express.cookieParser()); app.use(express.session({ secret: 'your secret here' })); app.use(app.router); }); app.get('/', function(req, res){ res.render('Hello world'); }); app.listen(3000);
  • 11. Routes function loadUser(req, res, next) { var user = users[req.params.id]; if (user) { req.user = user; next(); } else { next(new Error('Failed to load user ' + req.params.id)); } } app.get('/user/:id', loadUser, function(req, res){ res.send('Viewing user ' + req.user.name); });
  • 12. Cookie & Session function loadUser(req, res, next) { if (req.session.user) { return req.session.user; } var user = users[req.params.id]; if (user) { req.session.user = req.user = user; next(); } else { next(new Error('Failed to load user ' + req.params.id)); } }
  • 13. Do HTTP request • node http •
  • 14. request • git clone https://github.com/mikeal/ request.git • npm install request
  • 15. var request = require('request'); request( {uri:'http://www.google.com'}, function (error, response, body) { if (!error && response.statusCode == 200) { sys.puts(body) // Print the google web page. } })
  • 16. Template Engines • Haml • Jade • EJS • CoffeeKup •
  • 18. Stache • Stache is mustache.js for your node express apps app.set('view engine', 'mustache') app.register(".mustache", require('stache'));
  • 19. app.get('/', function (req, res) { res.render("index", { locals: { title: "Title content", body: "Page content" }, partials: { heading: '<title>{{title}}</title>' } }); }); <!-- index.mustache --> <html> <head> {{>heading}} </head> <body> {{{body}}} </body> </html>
  • 20. app.get('/', function (req, res) { res.render("index", { locals: { title: "Title content", body: "Page content" }, partials: { heading: '<title>{{title}}</title>' } }); }); <html> <head> <!-- index.mustache --> <title>Title content</title> <html> </head> <head> {{>heading}} </head> <body> Page content </body> <body> {{{body}}} </body> </html> </html>
  • 21.
  • 22. BUG
  • 25. node node
  • 26. node node 1. try{…} catch(error){…}
  • 27. node node 1. try{…} catch(error){…} 2. process.on('uncaughtException', function (err) {//doSomething}
  • 28. app.get("/err", function(req, res, next){ fs.readFile('file', function(err, data){ if (err) {throw err;} }); })
  • 29. app.get("/err", function(req, res, next){ fs.readFile('file', function(err, data){ if (err) {next(err);} }); })
  • 30. app.get("/err", function(req, res, next){ fs.readFile('file', function(err, data){ if (err) {next(err);} }); }) app.error(function(err, req, res){ console.err(err.stack); res.render("500.html", { locals: { page_title: '500_ _i ' }, status: 500 }); });
  • 31. express tips • try{}catch(e){} • routes callback error throw error next() express • uncaughtException node endless world
  • 33. Forever • • Github: https://github.com/indexzero/ forever • npm install forever • forever start app.js
  • 34. Thank You! PS: We Are Hiring! weibo.com/mengxy mengxy1987@gmail.com