SlideShare une entreprise Scribd logo
1  sur  29
Télécharger pour lire hors ligne
Introduction to buildREST API with
WhatisNode.js ? 
«Aplatform built onChrome's JavaScript runtime for easily building fast, scalable network applications.» http://nodejs.org/ 
Node.js isneithera server nora web framework
About Node.js 
•Createdby Ryan Dahl in 2009 
•Development and maintenance sponsored byJoyent 
•LicenceMIT 
•Last release : 0.10.31 
•Based on Google V8 Engine 
•+99 000 packages
Successstories 
Rails to Node 
« Servers were cut to 3 from 30 » 
« Running up to 20x faster in some scenarios » 
« Frontend and backend mobile teams could be combined […] » 
Java to Node 
« Built almost twice as fast with fewer people » 
« Double the requests per second » 
« 35% decrease in the average response time »
Architecture 
•Single Threaded 
•Event Loop 
•Non-blockingI/O 
•Javascript(Event DrivenLanguage)
Inside Node.js 
Standard JavaScript with 
•Buffer 
•C/C++ Addons 
•Child Processes 
•Cluster 
•Console 
•Crypto 
•Debugger 
•DNS 
•Domain 
•Events 
•File System 
•Globals 
•HTTP 
•HTTPS 
•Modules 
•Net 
•OS 
•Path 
•Process 
•Punycode 
•QueryStrings 
•Readline 
•REPL 
•Stream 
•String Decoder 
•Timers 
•TLS/SSL 
•TTY 
•UDP/Datagram 
•URL 
•Utilities 
•VM 
•ZLIB 
… but withoutDOM manipulation
File package.json 
Project informations 
•Name 
•Version 
•Dependencies 
•Licence 
•Main file 
•Etc...
NPM (NodePackagedModules) 
•Findpackages : https://www.npmjs.org/ 
•Help : npm-l 
•Createpackage.json: npminit 
•Install package : 
•npminstallexpress 
•npminstallmongosse--save 
•npminstall-g mocha 
•npm installgrunt--save-dev 
•Update project from package.json 
•npm install 
•npm update
Hello Node.js 
console.log("Hello World !"); 
hello.js 
> nodehello.js 
Hello World !
Loadmodule 
•Coremodule : var http = require('http'); 
•Project file module : var mymodule= require(‘./module’); // ./module.js or ./module/index.js var mymodule= require(‘../module.js’); var mymodule= require(‘/package.json’); 
•Packagedmodule (in node_modulesdirectory): var express = require(‘express’);
Createmodule 1/2 
var PI = Math.PI; 
exports.area= function(r) { 
return PI * r * r; 
}; 
var circle= require('./circle.js'); 
console.log('The area of a circle of radius 4 is '+ circle.area(4)); 
circle.js
Createmodule 2/2 
var PI = Math.PI; 
module.exports= function(r) { 
return PI * r * r; 
}; 
var circleArea= require('./circle-area.js'); 
console.log('The area of a circle of radius 4 is '+ circleArea(4)); 
circle-area.js
Node.js 
Talk is cheapShow me the code
Express introduction 
«Fast, unopinionated, minimalist web framework forNode.js» http://expressjs.com
Express sample 
var express = require('express'); 
var app= express(); 
app.get('/', function(req, res) { 
res.send('Hello World!'); 
}); 
app.post('/:name', function (req, res) { 
res.send('Hello !'+req.param('name')); 
}); 
app.listen(3000);
Express middleware 
Middleware can: 
•Execute any code. 
•Make changes to the request and the response objects. 
•End the request-response cycle. 
•Call the next middleware in the stack. 
var express = require('express'); 
var app= express(); 
var cookieParser= require('cookie-parser'); 
app.use(express.static(__dirname+ '/public')); 
app.use(cookieParser()); 
…
Express middleware modules 
Module 
Description 
morgan 
HTTP request logger middleware for node.js 
express.static 
Serve static content from the "public" directory (js, css, html, image, video, …) 
body-parser 
Parserequestbody and populatereq.body(ie: parsejsonbody) 
cookie-parser 
Parse cookie header and populate req.cookieswith an object keyed by the cookie names 
cookie-session 
Provide "guest" sessions, meaning any visitor will have a session, authenticated or not. 
express-session 
Providegenericsession functionality within-memorystorage by default 
method-override 
Lets you use HTTP verbs such as PUT or DELETE in places where the client doesn't support it. 
csurf 
Node.js CSRF protection middleware. 
…
Express router 
var express = require('express'); 
var router = express.Router(); 
router.get('/', function(req, res) { 
res.send('Hello World!'); 
}); 
router.post('/:name', function(req, res) { 
res.send('Hello !'+req.param('name')); 
}); 
var app= express(); 
app.use('/api/', router);
Express 
Talk is cheapShow me the code
Mongooseintroduction 
«Elegantmongodbobjectmodelingfornode.js » http://mongoosejs.com/
Mongooseconnect 
var mongoose= require('mongoose'); 
mongoose.connect('mongodb://localhost/test'); 
mongoose.connection.on('error', console.log); 
mongoose.connection.once('open', functioncallback (){ }); 
mongoose.connection.on('disconnected', functioncallback (){ });
Mongooseschema1/2 
/* Article Schema*/ 
var ArticleSchema= new Schema({ 
title: {type : String, trim : true}, 
body: {type : String, trim: true}, 
user: {type : Schema.ObjectId, ref: 'User'}, 
comments: [{ 
body: { type : String, default : '' }, 
user: { type : Schema.ObjectId, ref: 'User' }, 
createdAt: { type : Date, default : Date.now} 
}], 
createdAt: {type : Date, default : Date.now} 
}); 
/* Validations */ 
ArticleSchema.path('title').required(true, 'Article title cannot be blank'); 
ArticleSchema.path('body').required(true, 'Article body cannot be blank'); 
/* Save the Schema*/ 
mongoose.model('Article', ArticleSchema);
Mongooseschema2/2 
Othersschemafeatures: 
•Validator 
•Virtual property 
•Middleware 
•Population 
•…
Mongooseinstance & save 
/* Getthe model */ 
var Article = mongoose.model('Article'); 
/* Createa new instance */ 
var article = new Article({ 
title: 'Introduction to Mongoose', 
body : 'This is an article about Mongoose' 
}); 
/* Save the instance */ 
article.save(function(err){ 
if(err) return console.log("not saved !"); 
console.log("saved"); 
});
Mongoosequery 
var Article = mongoose.model('Article'); 
// A query 
Article 
.where('user').equals(myUserId) 
.where('tile', /mongoose/i) 
.select('titlebody createdAt') 
.sort('-createdAt') 
.limit(10) 
.exec (function (err, data){ /* do anything */ }); 
// The samequery 
Article.find({ 
user : myUserId, 
title: /mongoose/i 
}, 
'titlebody createdAt', 
{ 
sort : '-createdAt', 
limit: 10 
}, 
function (err, data){ /* do anything */ } 
);
Mongoose 
Talk is cheapShow me the code
Othersmodules 
•Web frameworksExpress, Koa, Sails, Hapi, Restify, … 
•Server toolsSocket.io, Passport, … 
•LoggersWinston, Bunyan, … 
•ToolsAsync, Q, Lodash, Moment, Cheerio, … 
•TestingNight Watch, Supertest, Mocha, Jasmine, Sinon, Chai, …
Questions?

Contenu connexe

Tendances

Tendances (20)

Introduction to Node JS.pdf
Introduction to Node JS.pdfIntroduction to Node JS.pdf
Introduction to Node JS.pdf
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Core java
Core javaCore java
Core java
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Testing with Spring: An Introduction
Testing with Spring: An IntroductionTesting with Spring: An Introduction
Testing with Spring: An Introduction
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Reactjs workshop (1)
Reactjs workshop (1)Reactjs workshop (1)
Reactjs workshop (1)
 
Angular modules in depth
Angular modules in depthAngular modules in depth
Angular modules in depth
 
Typescript ppt
Typescript pptTypescript ppt
Typescript ppt
 
Introduction to MERN Stack
Introduction to MERN StackIntroduction to MERN Stack
Introduction to MERN Stack
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introduction
 
Spring boot
Spring bootSpring boot
Spring boot
 
core java
core javacore java
core java
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
 
SOLID Design Principles applied in Java
SOLID Design Principles applied in JavaSOLID Design Principles applied in Java
SOLID Design Principles applied in Java
 

En vedette

Complete MVC on NodeJS
Complete MVC on NodeJSComplete MVC on NodeJS
Complete MVC on NodeJSHüseyin BABAL
 
Nodejs - Building a RESTful API
Nodejs - Building a RESTful APINodejs - Building a RESTful API
Nodejs - Building a RESTful APISang Cù
 
Create a RESTful API with NodeJS, Express and MongoDB
Create a RESTful API with NodeJS, Express and MongoDBCreate a RESTful API with NodeJS, Express and MongoDB
Create a RESTful API with NodeJS, Express and MongoDBHengki Sihombing
 
Introduction to Google API
Introduction to Google APIIntroduction to Google API
Introduction to Google APILakhdar Meftah
 
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012Dmytro Mindra
 
AllcountJS VTB24 loan сonveyor POC
AllcountJS VTB24 loan сonveyor POCAllcountJS VTB24 loan сonveyor POC
AllcountJS VTB24 loan сonveyor POCPavel Tiunov
 
Moscow js node.js enterprise development
Moscow js node.js enterprise developmentMoscow js node.js enterprise development
Moscow js node.js enterprise developmentPavel Tiunov
 
Learn Developing REST API in Node.js using LoopBack Framework
Learn Developing REST API  in Node.js using LoopBack FrameworkLearn Developing REST API  in Node.js using LoopBack Framework
Learn Developing REST API in Node.js using LoopBack FrameworkMarudi Subakti
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST APIFabien Vauchelles
 
ВВЕДЕНИЕ В NODE.JS
ВВЕДЕНИЕ В NODE.JS ВВЕДЕНИЕ В NODE.JS
ВВЕДЕНИЕ В NODE.JS Pavel Tsukanov
 
Архитектура программных систем на Node.js
Архитектура программных систем на Node.jsАрхитектура программных систем на Node.js
Архитектура программных систем на Node.jsTimur Shemsedinov
 
Асинхронность и параллелизм в Node.js
Асинхронность и параллелизм в Node.jsАсинхронность и параллелизм в Node.js
Асинхронность и параллелизм в Node.jsGeeksLab Odessa
 
Developing and Testing a MongoDB and Node.js REST API
Developing and Testing a MongoDB and Node.js REST APIDeveloping and Testing a MongoDB and Node.js REST API
Developing and Testing a MongoDB and Node.js REST APIAll Things Open
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsJakub Nesetril
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDDSudar Muthu
 
Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture AppDynamics
 
7 Stages of Scaling Web Applications
7 Stages of Scaling Web Applications7 Stages of Scaling Web Applications
7 Stages of Scaling Web ApplicationsDavid Mitzenmacher
 
Инфраструктура распределенных приложений на Node.js
Инфраструктура распределенных приложений на Node.jsИнфраструктура распределенных приложений на Node.js
Инфраструктура распределенных приложений на Node.jsStanislav Gumeniuk
 

En vedette (20)

Complete MVC on NodeJS
Complete MVC on NodeJSComplete MVC on NodeJS
Complete MVC on NodeJS
 
Nodejs - Building a RESTful API
Nodejs - Building a RESTful APINodejs - Building a RESTful API
Nodejs - Building a RESTful API
 
Create a RESTful API with NodeJS, Express and MongoDB
Create a RESTful API with NodeJS, Express and MongoDBCreate a RESTful API with NodeJS, Express and MongoDB
Create a RESTful API with NodeJS, Express and MongoDB
 
Introduction to Google API
Introduction to Google APIIntroduction to Google API
Introduction to Google API
 
Node.js (RichClient)
 Node.js (RichClient) Node.js (RichClient)
Node.js (RichClient)
 
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012
 
AllcountJS VTB24 loan сonveyor POC
AllcountJS VTB24 loan сonveyor POCAllcountJS VTB24 loan сonveyor POC
AllcountJS VTB24 loan сonveyor POC
 
Moscow js node.js enterprise development
Moscow js node.js enterprise developmentMoscow js node.js enterprise development
Moscow js node.js enterprise development
 
Learn Developing REST API in Node.js using LoopBack Framework
Learn Developing REST API  in Node.js using LoopBack FrameworkLearn Developing REST API  in Node.js using LoopBack Framework
Learn Developing REST API in Node.js using LoopBack Framework
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST API
 
ВВЕДЕНИЕ В NODE.JS
ВВЕДЕНИЕ В NODE.JS ВВЕДЕНИЕ В NODE.JS
ВВЕДЕНИЕ В NODE.JS
 
Архитектура программных систем на Node.js
Архитектура программных систем на Node.jsАрхитектура программных систем на Node.js
Архитектура программных систем на Node.js
 
Асинхронность и параллелизм в Node.js
Асинхронность и параллелизм в Node.jsАсинхронность и параллелизм в Node.js
Асинхронность и параллелизм в Node.js
 
Developing and Testing a MongoDB and Node.js REST API
Developing and Testing a MongoDB and Node.js REST APIDeveloping and Testing a MongoDB and Node.js REST API
Developing and Testing a MongoDB and Node.js REST API
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDD
 
REST API Design
REST API DesignREST API Design
REST API Design
 
Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture
 
7 Stages of Scaling Web Applications
7 Stages of Scaling Web Applications7 Stages of Scaling Web Applications
7 Stages of Scaling Web Applications
 
Инфраструктура распределенных приложений на Node.js
Инфраструктура распределенных приложений на Node.jsИнфраструктура распределенных приложений на Node.js
Инфраструктура распределенных приложений на Node.js
 

Similaire à Introduction to REST API with Node.js

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.jssoft-shake.ch
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1Mohammad Qureshi
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsasync_io
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineRicardo Silva
 
Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Ran Mizrahi
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Ran Mizrahi
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
Intro To Node.js
Intro To Node.jsIntro To Node.js
Intro To Node.jsChris Cowan
 
Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The WhenFITC
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.Mike Brevoort
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsOhad Kravchick
 
Introducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.jsIntroducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.jsRichard Rodger
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSocketsGonzalo Ayuso
 

Similaire à Introduction to REST API with Node.js (20)

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
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
 
Node azure
Node azureNode azure
Node azure
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Intro To Node.js
Intro To Node.jsIntro To Node.js
Intro To Node.js
 
Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The When
 
Node.js on Azure
Node.js on AzureNode.js on Azure
Node.js on Azure
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js Applications
 
NodeJS
NodeJSNodeJS
NodeJS
 
Introducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.jsIntroducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.js
 
20120816 nodejsdublin
20120816 nodejsdublin20120816 nodejsdublin
20120816 nodejsdublin
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
 
Nodejs web,db,hosting
Nodejs web,db,hostingNodejs web,db,hosting
Nodejs web,db,hosting
 

Plus de Yoann Gotthilf

Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJSYoann Gotthilf
 
Most Common JavaScript Mistakes
Most Common JavaScript MistakesMost Common JavaScript Mistakes
Most Common JavaScript MistakesYoann Gotthilf
 
Introduction to the MEAN stack
Introduction to the MEAN stackIntroduction to the MEAN stack
Introduction to the MEAN stackYoann Gotthilf
 
Web development - technologies and tools
Web development - technologies and toolsWeb development - technologies and tools
Web development - technologies and toolsYoann Gotthilf
 
Introduction à Android
Introduction à AndroidIntroduction à Android
Introduction à AndroidYoann Gotthilf
 
Développement Web - HTML5, CSS3, APIs Web
Développement Web - HTML5, CSS3, APIs WebDéveloppement Web - HTML5, CSS3, APIs Web
Développement Web - HTML5, CSS3, APIs WebYoann Gotthilf
 

Plus de Yoann Gotthilf (6)

Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
Most Common JavaScript Mistakes
Most Common JavaScript MistakesMost Common JavaScript Mistakes
Most Common JavaScript Mistakes
 
Introduction to the MEAN stack
Introduction to the MEAN stackIntroduction to the MEAN stack
Introduction to the MEAN stack
 
Web development - technologies and tools
Web development - technologies and toolsWeb development - technologies and tools
Web development - technologies and tools
 
Introduction à Android
Introduction à AndroidIntroduction à Android
Introduction à Android
 
Développement Web - HTML5, CSS3, APIs Web
Développement Web - HTML5, CSS3, APIs WebDéveloppement Web - HTML5, CSS3, APIs Web
Développement Web - HTML5, CSS3, APIs Web
 

Dernier

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...masabamasaba
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...masabamasaba
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in sowetomasabamasaba
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 

Dernier (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 

Introduction to REST API with Node.js

  • 2. WhatisNode.js ? «Aplatform built onChrome's JavaScript runtime for easily building fast, scalable network applications.» http://nodejs.org/ Node.js isneithera server nora web framework
  • 3. About Node.js •Createdby Ryan Dahl in 2009 •Development and maintenance sponsored byJoyent •LicenceMIT •Last release : 0.10.31 •Based on Google V8 Engine •+99 000 packages
  • 4. Successstories Rails to Node « Servers were cut to 3 from 30 » « Running up to 20x faster in some scenarios » « Frontend and backend mobile teams could be combined […] » Java to Node « Built almost twice as fast with fewer people » « Double the requests per second » « 35% decrease in the average response time »
  • 5. Architecture •Single Threaded •Event Loop •Non-blockingI/O •Javascript(Event DrivenLanguage)
  • 6.
  • 7. Inside Node.js Standard JavaScript with •Buffer •C/C++ Addons •Child Processes •Cluster •Console •Crypto •Debugger •DNS •Domain •Events •File System •Globals •HTTP •HTTPS •Modules •Net •OS •Path •Process •Punycode •QueryStrings •Readline •REPL •Stream •String Decoder •Timers •TLS/SSL •TTY •UDP/Datagram •URL •Utilities •VM •ZLIB … but withoutDOM manipulation
  • 8. File package.json Project informations •Name •Version •Dependencies •Licence •Main file •Etc...
  • 9. NPM (NodePackagedModules) •Findpackages : https://www.npmjs.org/ •Help : npm-l •Createpackage.json: npminit •Install package : •npminstallexpress •npminstallmongosse--save •npminstall-g mocha •npm installgrunt--save-dev •Update project from package.json •npm install •npm update
  • 10. Hello Node.js console.log("Hello World !"); hello.js > nodehello.js Hello World !
  • 11. Loadmodule •Coremodule : var http = require('http'); •Project file module : var mymodule= require(‘./module’); // ./module.js or ./module/index.js var mymodule= require(‘../module.js’); var mymodule= require(‘/package.json’); •Packagedmodule (in node_modulesdirectory): var express = require(‘express’);
  • 12. Createmodule 1/2 var PI = Math.PI; exports.area= function(r) { return PI * r * r; }; var circle= require('./circle.js'); console.log('The area of a circle of radius 4 is '+ circle.area(4)); circle.js
  • 13. Createmodule 2/2 var PI = Math.PI; module.exports= function(r) { return PI * r * r; }; var circleArea= require('./circle-area.js'); console.log('The area of a circle of radius 4 is '+ circleArea(4)); circle-area.js
  • 14. Node.js Talk is cheapShow me the code
  • 15. Express introduction «Fast, unopinionated, minimalist web framework forNode.js» http://expressjs.com
  • 16. Express sample var express = require('express'); var app= express(); app.get('/', function(req, res) { res.send('Hello World!'); }); app.post('/:name', function (req, res) { res.send('Hello !'+req.param('name')); }); app.listen(3000);
  • 17. Express middleware Middleware can: •Execute any code. •Make changes to the request and the response objects. •End the request-response cycle. •Call the next middleware in the stack. var express = require('express'); var app= express(); var cookieParser= require('cookie-parser'); app.use(express.static(__dirname+ '/public')); app.use(cookieParser()); …
  • 18. Express middleware modules Module Description morgan HTTP request logger middleware for node.js express.static Serve static content from the "public" directory (js, css, html, image, video, …) body-parser Parserequestbody and populatereq.body(ie: parsejsonbody) cookie-parser Parse cookie header and populate req.cookieswith an object keyed by the cookie names cookie-session Provide "guest" sessions, meaning any visitor will have a session, authenticated or not. express-session Providegenericsession functionality within-memorystorage by default method-override Lets you use HTTP verbs such as PUT or DELETE in places where the client doesn't support it. csurf Node.js CSRF protection middleware. …
  • 19. Express router var express = require('express'); var router = express.Router(); router.get('/', function(req, res) { res.send('Hello World!'); }); router.post('/:name', function(req, res) { res.send('Hello !'+req.param('name')); }); var app= express(); app.use('/api/', router);
  • 20. Express Talk is cheapShow me the code
  • 22. Mongooseconnect var mongoose= require('mongoose'); mongoose.connect('mongodb://localhost/test'); mongoose.connection.on('error', console.log); mongoose.connection.once('open', functioncallback (){ }); mongoose.connection.on('disconnected', functioncallback (){ });
  • 23. Mongooseschema1/2 /* Article Schema*/ var ArticleSchema= new Schema({ title: {type : String, trim : true}, body: {type : String, trim: true}, user: {type : Schema.ObjectId, ref: 'User'}, comments: [{ body: { type : String, default : '' }, user: { type : Schema.ObjectId, ref: 'User' }, createdAt: { type : Date, default : Date.now} }], createdAt: {type : Date, default : Date.now} }); /* Validations */ ArticleSchema.path('title').required(true, 'Article title cannot be blank'); ArticleSchema.path('body').required(true, 'Article body cannot be blank'); /* Save the Schema*/ mongoose.model('Article', ArticleSchema);
  • 24. Mongooseschema2/2 Othersschemafeatures: •Validator •Virtual property •Middleware •Population •…
  • 25. Mongooseinstance & save /* Getthe model */ var Article = mongoose.model('Article'); /* Createa new instance */ var article = new Article({ title: 'Introduction to Mongoose', body : 'This is an article about Mongoose' }); /* Save the instance */ article.save(function(err){ if(err) return console.log("not saved !"); console.log("saved"); });
  • 26. Mongoosequery var Article = mongoose.model('Article'); // A query Article .where('user').equals(myUserId) .where('tile', /mongoose/i) .select('titlebody createdAt') .sort('-createdAt') .limit(10) .exec (function (err, data){ /* do anything */ }); // The samequery Article.find({ user : myUserId, title: /mongoose/i }, 'titlebody createdAt', { sort : '-createdAt', limit: 10 }, function (err, data){ /* do anything */ } );
  • 27. Mongoose Talk is cheapShow me the code
  • 28. Othersmodules •Web frameworksExpress, Koa, Sails, Hapi, Restify, … •Server toolsSocket.io, Passport, … •LoggersWinston, Bunyan, … •ToolsAsync, Q, Lodash, Moment, Cheerio, … •TestingNight Watch, Supertest, Mocha, Jasmine, Sinon, Chai, …