Download presentation
Presentation is loading. Please wait.
Published byShawn Nelson Modified over 9 years ago
1
RESTful Web Development With Nodejs and Express
2
REST Stands for REpresentational State Transfer Has the following constraints: ◦Client-Server ◦Stateless ◦Cacheable ◦Layered System ◦Code on Demand ◦Uniform Interface
3
REST on the web Every kind of resource you want is at a different URI Interact with resources using the HTTP verbs ◦PUT (Create) ◦GET (Read) ◦POST (Update) ◦DELETE (Delete) The server does not keep track of state (except for authentication) The client manages the logic of the application.
4
REST Examples Assume we are making an app to track what people we meet with ◦We need the following resources: ◦Users ◦Meetings ◦We might use the following URIs ◦GET /user(list all users) ◦POST/user/1(get information about user with ID 1) ◦PUT /meeting(create a new meeting) ◦DELETE /meeting /5(delete meeting with ID 5) ◦The responses are usually JSON, e.g. { 'id': 1, 'name': 'John MacDonald', 'hometown': 'Halifax', 'occupation': 'Farmer' }
5
Using NodeJS NodeJS is just a JavaScript interpreter. It comes with a package manager called npm ◦Install packages like this: npm install ◦This will install it in the current folder. ◦To install globally, do npm install –g To use Node as a webserver, you must write an application that responds to web requests. Node has a library (HTTP) for doing this, but it’s easier to use a framework, like Express To access a library, use the require() function
6
Using Express Express is just a package for Node ◦Create a new web application with var app = express(); ◦Respond to requests like app.get('/user', function(req, res){ ◦Look at parameters through the req object ◦ req.params for query parameters ◦ req.body for post fields ◦ req.files for files ◦Send responses through the res object ◦ res.send("Hi mom!") ◦Start the application with ◦ app.listen( )
7
Client-Server Communication On the client side, use XMLHttpRequest (or jQuery) If you are not getting your data from the same place as your page, then you will have to use Cross Origin Resource Sharing (CORS) var xhr = new XMLHttpRequest(); //Might also use onreadystatechange xhr.onload = function() { var responseObject = JSON.parse(this.responseText); }; xhr.open('get', 'user'); xhr.send();
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.