Transcript Servers

RESTful Web
Development With
Nodejs and Express
REST
• Stands for REpresentational State Transfer
• Has the following constraints:
◦
◦
◦
◦
◦
◦
Client-Server
Stateless
Cacheable
Layered System
Code on Demand
Uniform Interface
REST on the web
• Every kind of resource you want is at a different URI
• Interact with resources using the HTTP verbs
◦
◦
◦
◦
PUT
GET
POST
DELETE
(Create)
(Read)
(Update)
(Delete)
• The server does not keep track of state (except for authentication)
• The client manages the logic of the application.
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'
}
Using NodeJS
• NodeJS is just a JavaScript interpreter.
• It comes with a package manager called npm
◦ Install packages like this: npm install <package_name>
◦ This will install it in the current folder.
◦ To install globally, do npm install –g <package_name>
• 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
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(<port>)
Client-Server Communication
• On the client side, use XMLHttpRequest (or jQuery)
var xhr = new XMLHttpRequest();
//Might also use onreadystatechange
xhr.onload = function() {
var responseObject = JSON.parse(this.responseText);
};
xhr.open('get', 'user');
xhr.send();
• 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)