JavaScript Workshop
1. HTTP
2. AJAX
3. CORS
SERVER
Client
Client
Client
Client
HTTP Request
Starting line
POST /users HTTP/1.1
Headers
Host: apis.example.org
User-Agent: Mozilla/5.0 ...
Accept: text/html
Connection: close
Body
...
HTTP Response
Starting line
HTTP/1.1 200 OK
Headers
Date: Wed, 11 Feb 2009 11:20:59 GMT
Server: Apache
X-Powered-By: PHP/5.2.4-2ubuntu5wm1
Last-Modified: Wed, 11 Feb 2009 11:20:59 GMT
Content-Language: ru
Content-Type: text/html; charset=utf-8
Content-Length: 1234
Connection: close
Body
...
Set-Cookie: RMID=732423sdfs73242;
expires=Fri, 31 Dec 2010 23:59:59 GMT;
path=/; domain=.example.net
GET /path/resource?param1=value1¶m2=value2
Idempotent
No Body
Might be cached
POST /path/resource
Not Idempotent
Body Available
Should not be cached
PATCH /path/resource/:id
Not Idempotent
Body Available
Should not be cached
PUT /path/resource/:id
Idempotent
Body Available
Should not be cached
DELETE /path/resource/:id
Idempotent
Body Available
Should not be cached
HEAD /path/resource
Idempotent
No Body
Can be cached
OPTIONS /path/resource
Idempotent
No Body
GET HEAD OPTIONS
Safe methods are intended only for information retrieval and should not change the state of the server. They should not have side effects, beyond relatively harmless effects such as logging, caching, the serving of banner advertisements or incrementing a web counter.
Not mandated by the standard!
10x | Information |
2xx | Success |
30x | Redirect |
4xx | Client Error |
5xx | Server Error |
101 Switching Protocols
This means the requester has asked the server to switch protocols and the server is acknowledging that it will do so.
200 OK
Standard response for successful HTTP requests. The actual response will depend on the request method used.
201 Created
The request has been fulfilled and resulted in a new resource being created.
202 Accepted
The request has been accepted for processing, but the processing has not been completed.
204 No Content
The server successfully processed the request, but is not returning any content
This class of status code indicates the client must take additional action to complete the request.
301 Moved Permanently
This and all future requests should be directed to the given URI.
Works automatically for Browser requests. Won't work for AJAX.
304 Not Modified
Indicates that the resource has not been modified since the version specified by the request headers If-Modified-Since or If-None-Match. This means that there is no need to retransmit the resource, since the client still has a previously-downloaded copy.
400 Bad Request
The server cannot or will not process the request due to something that is perceived to be a client error.
404 Not Found
The requested resource could not be found but may be available again in the future.
401 Unauthorized / 403 Forbidden
410 Gone
Indicates that the resource requested is no longer available and will not be available again.
500 Internal Server Error
A generic error message, given when an unexpected condition was encountered and no more specific message is suitable.
504 Gateway Timeout
A server is acting as a gateway or proxy to fulfill the request by the client to access the requested URL. This server did not receive a timely response from an upstream server it accessed to deal with your HTTP request.
Connection: keep-alive
AJAX is a set of web development techniques utilizing many web technologies used on the client-side to create asynchronous Web applications.
var xhr = new XMLHttpRequest();
xhr.open('get', 'path/resource');
xhr.onreadystatechange = function () {
// readyState 4 means the request is done.
var DONE = 4;
// status 200 is a successful return.
var OK = 200;
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
alert(xhr.responseText);
} else {
alert('Error: ' + xhr.status);
}
}
};
xhr.send(null);
Pros:
Cons:
$.ajax("https://example.com")
.success(function(data, textStatus, jqXHR){
//do something
}).error(function(jqXHR, textStatus, errorThrown){
//handle error
});
$.ajax({
url:"https://example.com",
method: "POST",
async: true,
data: { "message": "my custom data" }
}).success(function(data, textStatus, jqXHR){
//do something
}).error(function(jqXHR, textStatus, errorThrown){
//handle error
});
request
.post('https://example.com')
.send({ "message": "my custom data" })
.set('X-API-Key', 'foobar')
.set('Accept', 'application/json')
.end(function(err, res){
if (res.ok) {
alert('yay got ' + JSON.stringify(res.body));
} else {
alert('Oh no! error ' + res.text);
}
});
api.example.com
example.com/index.html
AJAX won't work
Preflight Request (OPTIONS)
OPTIONS /cors HTTP/1.1
Origin: http://api.example.com
Access-Control-Request-Method:
PUT
Access-Control-Request-Headers:
X-Custom-Header
Host: example.com
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0...
AJAX Request
var url = 'http://api.example.com';
var xhr = createCORSRequest('PUT', url);
xhr.setRequestHeader(
'X-Custom-Header', 'value');
xhr.send();
Preflight Response (OPTIONS)
Access-Control-Allow-Origin:
http://api.bob.com
Access-Control-Allow-Methods:
GET, POST, PUT
Access-Control-Allow-Headers:
X-Custom-Header
Content-Type:
text/html; charset=utf-8
api.example.com
example.com/index.html
No cookies and some headers are missing
CORS
xhr.withCredentials = true;
XMLHttpRequest cannot load http://api.example.com. Origin http://api.bob.com is not allowed by Access-Control-Allow-Origin.