use node.js to create a rest api

54
NODE.JS

Upload: fabien-vauchelles

Post on 18-Jul-2015

776 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Use Node.js to create a REST API

NODE.JS

Page 2: Use Node.js to create a REST API

INTRODUCTION

Page 3: Use Node.js to create a REST API

WHAT IS NODE.JS ?Node.JS is the Javascript engine of Chrome, port to be used

from the command line.

Page 4: Use Node.js to create a REST API

ABOUT NODE.JSCreated by Ryan Dahl in 2009Licence MITBased on Google Chrome V8 Engine

Page 5: Use Node.js to create a REST API

BASICS

Page 6: Use Node.js to create a REST API

ARCHITECTURESingle ThreadedEvent LoopNon‐blocking I/OJavascript (Event Driven Language)

Page 7: Use Node.js to create a REST API

NODE.JS SYSTEM

Page 8: Use Node.js to create a REST API

HELLO WORLD IN NODE.JShello.js

console.log('Hello World!');

$ node hello.js> Hello World!

Page 9: Use Node.js to create a REST API

DON'T FORGET THE DEMO.DON'T FORGET THE DEMO.

Page 10: Use Node.js to create a REST API

MODULES / LOAD

Load a core module or a packaged module(in node_modules directory)

var http = require('http');

Load from your projectvar mymodule = require('./mymodule');

Page 11: Use Node.js to create a REST API

MODULES / CREATE

speaker.jsmodule.exports = { sayHi: sayHi}

function sayHi() { console.log('hi!'); }

example.jsvar speaker = require('./speaker');

speaker.sayHi();

Page 12: Use Node.js to create a REST API

YOU PREPARE A DEMO,YOU PREPARE A DEMO,DON'T U ?DON'T U ?

Page 13: Use Node.js to create a REST API

ERROR-FIRST CALLBACKSThe first argument of the callback is always reserved

for an error object:fs.readFile('/foo.txt', function(err, data) { if (err) { console.log('Ahh! An Error!'); return; }

console.log(data);});

Page 14: Use Node.js to create a REST API

EXPRESS FRAMEWORK

Page 15: Use Node.js to create a REST API

WHAT IS IT ?"Fast, unopinionated, minimalist web framework for Node.js"

(expressjs.com)

Page 16: Use Node.js to create a REST API

HELLO WORLD IN EXPRESSvar express = require('express');var app = express();

app.get('/', function(req, res) { res.send('Hello World!');});

app.listen(9001);

Don’t forget:$ npm install express

Page 17: Use Node.js to create a REST API

LIVE DEMO ?LIVE DEMO ?

Page 18: Use Node.js to create a REST API

MIDDLEWARE / WHAT ?

Middlewares can :make changes to the request and the response objectsend the request

Page 19: Use Node.js to create a REST API

MIDDLEWARE / PIPE

Middlewares are in a pipe

var bodyParser = require('body-parser');var cookieParser = require('cookie-parser');var errorHandler = require('errorhandler'),

var app = express();app.use(bodyParser.json());app.use(cookieParser());app.use(errorHandler());

Page 20: Use Node.js to create a REST API

MIDDLEWARE / STANDARD MODULES

body‐parser Parse request body and populate req.body

cookie‐parser Parse cookie header and populatereq.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 theclient doesn't support it

Page 21: Use Node.js to create a REST API

ROUTER / HELLO WORLD

api‐hello.jsvar express = require('express');var router = express.Router();

router.get('/', function(req, res) { res.send('Hello World!');});

module.exports = router;

index.jsvar express = require('express');var app = express();

// Routesapp.use('/hello', require('./api-hello'));

app.listen(9001);

Page 22: Use Node.js to create a REST API

CHOOSE THE DEMO PILL !CHOOSE THE DEMO PILL !

Page 23: Use Node.js to create a REST API

ROUTER / WHY ?

Routers help to split the code in modules

Page 24: Use Node.js to create a REST API

MONGOOSE

Page 25: Use Node.js to create a REST API

WHAT IS IT ?Mongoose is a Node.js connector for MongoDB.

Page 26: Use Node.js to create a REST API

CONNECT TO MONGODBvar mongoose = require('mongoose');mongoose.connect('mongodb://localhost/test');

Page 27: Use Node.js to create a REST API

SCHEMADefine the format of a document with a schema :

var StudentSchema = new mongoose.Schema({ name: String, age: Number course: [String], address: { city: String, country: String }});

var Student = mongoose.model('Student', StudentSchema);

Page 28: Use Node.js to create a REST API

CREATE OR UPDATE ITEMvar student = new Student({ name: 'Serge', age: 23, course: ['AngularJS', 'Node.js'], address: { city: 'Paris', country: 'France' }});

student.save(function(err) { if (err) return console.log('not saved!'); console.log('saved');});

Page 29: Use Node.js to create a REST API

REMOVE ITEMstudent.remove(function(err) { if (err) return console.log('not removed!'); console.log('removed');});

Page 30: Use Node.js to create a REST API

FIND ITEMSStudent.findOne({name: 'Serge'}, function(err, student) { // student is an Student object});

Page 31: Use Node.js to create a REST API

MEAN STACK

Page 32: Use Node.js to create a REST API

WHAT IS IT ?MEAN stands for :MongoDBExpress frameworkAngularJSNodeJS

Page 33: Use Node.js to create a REST API

PROJECT STRUCTUREroot|- api : all routes and processing |- thing.js : an route example|- node_modules : external librairies|- index.js : configuration and main application|- package.json : list of external librairies

Page 34: Use Node.js to create a REST API

INDEX.JS4 parts :

1.  Connect to the Database2.  Configure Express framework3.  Define routes4.  Start the server

Page 35: Use Node.js to create a REST API

HE HAS PROMISED USHE HAS PROMISED USAN EXAMPLE, RIGHT?AN EXAMPLE, RIGHT?

Page 36: Use Node.js to create a REST API

ROUTE EXAMPLE1.  Define routes2.  Define model3.  Define processing

Page 37: Use Node.js to create a REST API

DID HE FORGETDID HE FORGETTHE EXAMPLE ?THE EXAMPLE ?

Page 38: Use Node.js to create a REST API

TEST YOUR API !

Page 39: Use Node.js to create a REST API

POSTMANUse Postman extension for Chrome (packaged app)

Page 40: Use Node.js to create a REST API

GO FURTHERNodeSchool.io (learn you node)

Page 41: Use Node.js to create a REST API

TUTORIAL

Page 42: Use Node.js to create a REST API

TUTORIAL / GET THE PROJECT

GET THE PROJECT$ git clone https://github.com/fabienvauchelles/stweb-angularjs-tutorial.git$ cd stweb-angularjs-tutorial/backend

Page 43: Use Node.js to create a REST API

TUTORIAL / SERVER

GET THE NEXT STEP$ git reset --hard q15$ npm install

CREATE A SERVERFill backend/app.js

Page 44: Use Node.js to create a REST API

TUTORIAL / FIRST ROUTE

GET THE NEXT STEP$ git reset --hard q16

CREATE THE 'FINDALL' ROUTE1.  Create a findAll function (node format) to return a list ofarticle

2.  Add findAll to the router3.  Add the articles route to backend/app.js

Page 45: Use Node.js to create a REST API

TUTORIAL / ROUTE 'CREATE'

GET THE NEXT STEP$ git reset --hard q17

CREATE THE 'CREATE' ROUTE1.  Create a create function (node format) to create an articlefrom req.body

2.  Add create to the router (HTTP POST)

Page 46: Use Node.js to create a REST API

TUTORIAL / ROUTE 'DELETE'

GET THE NEXT STEP$ git reset --hard q18

CREATE THE 'DELETE' ROUTE1.  Create a destroy function (node format) to remove an article(id in the url)

2.  Add destroy to the router (HTTP DELETE)

Page 47: Use Node.js to create a REST API

TUTORIAL / IMPORT DATA

START MONGODBIn a new shell :

$ mongod

Page 48: Use Node.js to create a REST API

TUTORIAL / MONGOOSE

GET THE NEXT STEP$ git reset --hard q19

IMPORT DATA$ mongoimport --db postagram --collection articles --file articles-init.json

ADD MONGOOSE TO THE PROJECT$ npm install mongoose --save

Page 49: Use Node.js to create a REST API

TUTORIAL / CONNECT

GET THE NEXT STEP$ git reset --hard q20

CONNECT SERVER TO MONGODBAdd connect in backend/app.js

Page 50: Use Node.js to create a REST API

TUTORIAL / FINDALL

GET THE NEXT STEP$ git reset --hard q21

USE MONGOOSE FOR FINDALL1.  Comment create & destroy route (and function)2.  Import mongoose with require3.  Replace article static model with a mongoose schema4.  Use mongoose to implement findAll

Page 51: Use Node.js to create a REST API

TUTORIAL / SEARCH

GET THE NEXT STEP$ git reset --hard q22

REPLACE FINDALL BY SEARCHUse a MongoDB filter to search on title.Bonus: filter on description and tags

Page 52: Use Node.js to create a REST API

TUTORIAL / ROUTE 'CREATE'

GET THE NEXT STEP$ git reset --hard q23

IMPLEMENT CREATE1.  Use mongoose to implement create2.  Uncomment the create route

Page 53: Use Node.js to create a REST API

TUTORIAL / ROUTE 'DELETE'

GET THE NEXT STEP$ git reset --hard q24

IMPLEMENT DELETE1.  Use mongoose to implement delete2.  Uncomment the delete route

Page 54: Use Node.js to create a REST API

© Fabien Vauchelles (2015)

TUTORIAL / FINAL

GET AND READ THE SOLUCE$ git reset --hard q25