SlideShare a Scribd company logo
NODE.JS
INTRODUCTION
WHAT IS NODE.JS ?
Node.JS is the Javascript engine of Chrome, port to be used
from the command line.
ABOUT NODE.JS
Created by Ryan Dahl in 2009
Licence MIT
Based on Google Chrome V8 Engine
BASICS
ARCHITECTURE
Single Threaded
Event Loop
Non‐blocking I/O
Javascript (Event Driven Language)
NODE.JS SYSTEM
HELLO WORLD IN NODE.JS
hello.js
console.log('HelloWorld!');
$nodehello.js
>HelloWorld!
DON'T FORGET THE DEMO.DON'T FORGET THE DEMO.
MODULES / LOAD
Load a core module or a packaged module
(in node_modules directory)
varhttp=require('http');
Load from your project
varmymodule=require('./mymodule');
MODULES / CREATE
speaker.js
module.exports={
sayHi:sayHi
}
functionsayHi(){console.log('hi!');}
example.js
varspeaker=require('./speaker');
speaker.sayHi();
YOU PREPARE A DEMO,YOU PREPARE A DEMO,
DON'T U ?DON'T U ?
ERROR-FIRST CALLBACKS
The first argument of the callback is always reserved
for an error object:
fs.readFile('/foo.txt',function(err,data){
if(err){
console.log('Ahh!AnError!');
return;
}
console.log(data);
});
EXPRESS FRAMEWORK
WHAT IS IT ?
"Fast, unopinionated, minimalist web framework for Node.js"
(expressjs.com)
HELLO WORLD IN EXPRESS
varexpress=require('express');
varapp=express();
app.get('/',function(req,res){
res.send('HelloWorld!');
});
app.listen(9001);
Don’t forget:
$npminstallexpress
LIVE DEMO ?LIVE DEMO ?
MIDDLEWARE / WHAT ?
Middlewares can :
make changes to the request and the response objects
end the request
MIDDLEWARE / PIPE
Middlewares are in a pipe
varbodyParser=require('body-parser');
varcookieParser=require('cookie-parser');
varerrorHandler=require('errorhandler'),
varapp=express();
app.use(bodyParser.json());
app.use(cookieParser());
app.use(errorHandler());
MIDDLEWARE / STANDARD MODULES
body‐parser Parse request body and populate req.body
cookie‐parser
Parse cookie header and populate
req.cookies
cors Allow CORS requests
errorhandler
Send a full stack trace of error to the client.
Has to be last
express.static
Serve static content from the "public"
directory (html, css, js, etc.)
method‐override
Lets you use PUT and DELETE where the
client doesn't support it
ROUTER / HELLO WORLD
api‐hello.js
varexpress=require('express');
varrouter=express.Router();
router.get('/',function(req,res){
res.send('HelloWorld!');
});
module.exports=router;
index.js
varexpress=require('express');
varapp=express();
//Routes
app.use('/hello',require('./api-hello'));
app.listen(9001);
CHOOSE THE DEMO PILL !CHOOSE THE DEMO PILL !
ROUTER / WHY ?
Routers help to split the code in modules
MONGOOSE
WHAT IS IT ?
Mongoose is a Node.js connector for MongoDB.
CONNECT TO MONGODB
varmongoose=require('mongoose');
mongoose.connect('mongodb://localhost/test');
SCHEMA
Define the format of a document with a schema :
varStudentSchema=newmongoose.Schema({
name:String,
age:Number
course:[String],
address:{
city:String,
country:String
}
});
varStudent=mongoose.model('Student',StudentSchema);
CREATE OR UPDATE ITEM
varstudent=newStudent({
name:'Serge',
age:23,
course:['AngularJS','Node.js'],
address:{
city:'Paris',
country:'France'
}
});
student.save(function(err){
if(err)returnconsole.log('notsaved!');
console.log('saved');
});
REMOVE ITEM
student.remove(function(err){
if(err)returnconsole.log('notremoved!');
console.log('removed');
});
FIND ITEMS
Student.findOne({name:'Serge'},function(err,student){
//studentisanStudentobject
});
MEAN STACK
WHAT IS IT ?
MEAN stands for :
MongoDB
Express framework
AngularJS
NodeJS
PROJECT STRUCTURE
root
|-api :allroutesandprocessing
|-thing.js :anrouteexample
|-node_modules :externallibrairies
|-index.js :configurationandmainapplication
|-package.json :listofexternallibrairies
INDEX.JS
4 parts :
1.  Connect to the Database
2.  Configure Express framework
3.  Define routes
4.  Start the server
HE HAS PROMISED USHE HAS PROMISED US
AN EXAMPLE, RIGHT?AN EXAMPLE, RIGHT?
ROUTE EXAMPLE
1.  Define routes
2.  Define model
3.  Define processing
DID HE FORGETDID HE FORGET
THE EXAMPLE ?THE EXAMPLE ?
TEST YOUR API !
POSTMAN
Use Postman extension for Chrome (packaged app)
GO FURTHER
NodeSchool.io (learn you node)
TUTORIAL
TUTORIAL / GET THE PROJECT
GET THE PROJECT
$gitclonehttps://github.com/fabienvauchelles/stweb-angularjs-tutorial.git
$cdstweb-angularjs-tutorial/backend
TUTORIAL / SERVER
GET THE NEXT STEP
$gitreset--hardq15
$npminstall
CREATE A SERVER
Fill backend/app.js
TUTORIAL / FIRST ROUTE
GET THE NEXT STEP
$gitreset--hardq16
CREATE THE 'FINDALL' ROUTE
1.  Create a findAll function (node format) to return a list of
article
2.  Add findAll to the router
3.  Add the articles route to backend/app.js
TUTORIAL / ROUTE 'CREATE'
GET THE NEXT STEP
$gitreset--hardq17
CREATE THE 'CREATE' ROUTE
1.  Create a create function (node format) to create an article
from req.body
2.  Add create to the router (HTTP POST)
TUTORIAL / ROUTE 'DELETE'
GET THE NEXT STEP
$gitreset--hardq18
CREATE THE 'DELETE' ROUTE
1.  Create a destroy function (node format) to remove an article
(id in the url)
2.  Add destroy to the router (HTTP DELETE)
TUTORIAL / IMPORT DATA
START MONGODB
In a new shell :
$mongod
TUTORIAL / MONGOOSE
GET THE NEXT STEP
$gitreset--hardq19
IMPORT DATA
$mongoimport--dbpostagram--collectionarticles
--filearticles-init.json
ADD MONGOOSE TO THE PROJECT
$npminstallmongoose--save
TUTORIAL / CONNECT
GET THE NEXT STEP
$gitreset--hardq20
CONNECT SERVER TO MONGODB
Add connect in backend/app.js
TUTORIAL / FINDALL
GET THE NEXT STEP
$gitreset--hardq21
USE MONGOOSE FOR FINDALL
1.  Comment create & destroy route (and function)
2.  Import mongoose with require
3.  Replace article static model with a mongoose schema
4.  Use mongoose to implement findAll
TUTORIAL / SEARCH
GET THE NEXT STEP
$gitreset--hardq22
REPLACE FINDALL BY SEARCH
Use a MongoDB filter to search on title.
Bonus: filter on description and tags
TUTORIAL / ROUTE 'CREATE'
GET THE NEXT STEP
$gitreset--hardq23
IMPLEMENT CREATE
1.  Use mongoose to implement create
2.  Uncomment the create route
TUTORIAL / ROUTE 'DELETE'
GET THE NEXT STEP
$gitreset--hardq24
IMPLEMENT DELETE
1.  Use mongoose to implement delete
2.  Uncomment the delete route
© Fabien Vauchelles (2015)
TUTORIAL / FINAL
GET AND READ THE SOLUCE
$gitreset--hardq25

More Related Content

PPTX
Node.js Express
PPTX
Rest api with node js and express
PDF
Nodejs presentation
PPT
ASP.NET MVC Presentation
PPTX
Introduction to Node.js
PDF
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
PDF
NodeJS for Beginner
PDF
Spring Framework - Core
Node.js Express
Rest api with node js and express
Nodejs presentation
ASP.NET MVC Presentation
Introduction to Node.js
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
NodeJS for Beginner
Spring Framework - Core

What's hot (20)

PPTX
Node js introduction
PDF
React and redux
PPTX
React workshop presentation
PDF
An introduction to React.js
PDF
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
PPT
Angular 8
PPTX
Introduction to DOM
PDF
Spring boot introduction
PPTX
React hooks
PDF
JavaScript Fetch API
PPTX
Introduction to react_js
PPT
React js
PDF
Java entreprise edition et industrialisation du génie logiciel par m.youssfi
PDF
How to Build Real-time Chat App with Express, ReactJS, and Socket.IO?
PPT
CSS
PPTX
Introduction Node.js
PPTX
NodeJS - Server Side JS
PDF
[24]안드로이드 웹뷰의 모든것
PPTX
PDF
Spring Boot
Node js introduction
React and redux
React workshop presentation
An introduction to React.js
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
Angular 8
Introduction to DOM
Spring boot introduction
React hooks
JavaScript Fetch API
Introduction to react_js
React js
Java entreprise edition et industrialisation du génie logiciel par m.youssfi
How to Build Real-time Chat App with Express, ReactJS, and Socket.IO?
CSS
Introduction Node.js
NodeJS - Server Side JS
[24]안드로이드 웹뷰의 모든것
Spring Boot
Ad

Viewers also liked (15)

PDF
Writing RESTful web services using Node.js
PPTX
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012
PPT
Node.js (RichClient)
PDF
AllcountJS VTB24 loan сonveyor POC
PDF
Moscow js node.js enterprise development
PPTX
Learn Developing REST API in Node.js using LoopBack Framework
PPT
ВВЕДЕНИЕ В NODE.JS
PDF
Introduction to REST API with Node.js
ODP
Архитектура программных систем на Node.js
PDF
Асинхронность и параллелизм в Node.js
PDF
Developing and Testing a MongoDB and Node.js REST API
PDF
Building Killer RESTful APIs with NodeJs
PDF
Anatomy of a Modern Node.js Application Architecture
PDF
REST: From GET to HATEOAS
PDF
Инфраструктура распределенных приложений на Node.js
Writing RESTful web services using Node.js
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012
Node.js (RichClient)
AllcountJS VTB24 loan сonveyor POC
Moscow js node.js enterprise development
Learn Developing REST API in Node.js using LoopBack Framework
ВВЕДЕНИЕ В NODE.JS
Introduction to REST API with Node.js
Архитектура программных систем на Node.js
Асинхронность и параллелизм в Node.js
Developing and Testing a MongoDB and Node.js REST API
Building Killer RESTful APIs with NodeJs
Anatomy of a Modern Node.js Application Architecture
REST: From GET to HATEOAS
Инфраструктура распределенных приложений на Node.js
Ad

Similar to Use Node.js to create a REST API (20)

PDF
IOC + Javascript
PPTX
Intro To Node.js
PPT
Nodejs Intro Part One
PDF
5.node js
PPTX
Introduction to Node.js
ODP
Node js presentation
PPTX
Introduction to node.js GDD
PDF
Android and the Seven Dwarfs from Devox'15
PDF
A I R Presentation Dev Camp Feb 08
PDF
Asynchronous Module Definition (AMD)
PPTX
Basic Concept of Node.js & NPM
PDF
soft-shake.ch - Hands on Node.js
KEY
Modules and EmbedJS
PDF
All aboard the NodeJS Express
PDF
NodeJS: n00b no more
PPTX
[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova
PPTX
AngularJS Internal
PPTX
AngularJS Architecture
PPTX
hacking with node.JS
PDF
Node Web Development 2nd Edition: Chapter1 About Node
IOC + Javascript
Intro To Node.js
Nodejs Intro Part One
5.node js
Introduction to Node.js
Node js presentation
Introduction to node.js GDD
Android and the Seven Dwarfs from Devox'15
A I R Presentation Dev Camp Feb 08
Asynchronous Module Definition (AMD)
Basic Concept of Node.js & NPM
soft-shake.ch - Hands on Node.js
Modules and EmbedJS
All aboard the NodeJS Express
NodeJS: n00b no more
[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova
AngularJS Internal
AngularJS Architecture
hacking with node.JS
Node Web Development 2nd Edition: Chapter1 About Node

More from Fabien Vauchelles (9)

PDF
Design a landing page
PDF
Using MongoDB
PDF
De l'idée au produit en lean startup IT
PDF
Créer une startup
PDF
What is NoSQL ?
PDF
Create a landing page
PDF
Master AngularJS
PDF
Discover AngularJS
PPTX
Comment OAuth autorise ces applications à accéder à nos données privées ?
Design a landing page
Using MongoDB
De l'idée au produit en lean startup IT
Créer une startup
What is NoSQL ?
Create a landing page
Master AngularJS
Discover AngularJS
Comment OAuth autorise ces applications à accéder à nos données privées ?

Recently uploaded (20)

PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
PPT
Teaching material agriculture food technology
PDF
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
PDF
Transforming Manufacturing operations through Intelligent Integrations
PDF
Advanced IT Governance
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
NewMind AI Monthly Chronicles - July 2025
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
Cloud computing and distributed systems.
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Advanced Soft Computing BINUS July 2025.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Teaching material agriculture food technology
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
Transforming Manufacturing operations through Intelligent Integrations
Advanced IT Governance
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
NewMind AI Monthly Chronicles - July 2025
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
NewMind AI Weekly Chronicles - August'25 Week I
Cloud computing and distributed systems.
“AI and Expert System Decision Support & Business Intelligence Systems”
Understanding_Digital_Forensics_Presentation.pptx
MYSQL Presentation for SQL database connectivity
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
The Rise and Fall of 3GPP – Time for a Sabbatical?
Advanced Soft Computing BINUS July 2025.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...

Use Node.js to create a REST API