HyperText Transfer Protocol
JavaScript Workshop
Contents
1. HTTP
2. AJAX
3. CORS
Transfer
HyperText
Protocol
HYPERTEXT TRANSFER PROTOCOL
SERVER
Client
Client
Client
Client
HyperText Transfer Protocol
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
...
HyperText Transfer Protocol
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
...
Cookie
Set-Cookie: RMID=732423sdfs73242;
expires=Fri, 31 Dec 2010 23:59:59 GMT;
path=/; domain=.example.net
HTTP Methods
GET
GET /path/resource?param1=value1¶m2=value2
Idempotent
- The GET method requests a representation of the specified resource.
- Requests using GET should only retrieve data and should have no other effect.
No Body
Might be cached
HTTP Methods
POST
POST /path/resource
Not Idempotent
- The POST method requests that the server accept the entity enclosed in the request as a new subordinate of the web resource identified by the URI.
Body Available
Should not be cached
HTTP Methods
PATCH
PATCH /path/resource/:id
Not Idempotent
- The PATCH method applies partial modifications to a resource
Body Available
Should not be cached
HTTP Methods
PUT
PUT /path/resource/:id
Idempotent
- The PUT method requests that the enclosed entity be stored under the supplied URI.
- If the URI refers to an already existing resource, it is modified.
- If the URI does not point to an existing resource, then the server can create the resource with that URI.
Body Available
Should not be cached
HTTP Methods
DELETE
DELETE /path/resource/:id
Idempotent
- The DELETE method deletes the specified resource.
Body Available
Should not be cached
HTTP Methods
HEAD
HEAD /path/resource
Idempotent
- The HEAD method asks for a response identical to that of a GET request, but without the response body.
No Body
Can be cached
HTTP Methods
OPTIONS
OPTIONS /path/resource
Idempotent
- The OPTIONS method returns the HTTP methods that the server supports for the specified URL.
No Body
Safe Methods
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!
STATUS CODES
10x | Information |
2xx | Success |
30x | Redirect |
4xx | Client Error |
5xx | Server Error |
STATUS CODES - 10x
101 Switching Protocols
This means the requester has asked the server to switch protocols and the server is acknowledging that it will do so.
STATUS CODES - 2xx
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
STATUS CODES - 30x
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.
STATUS CODES - 4xx
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.
STATUS CODES - 5xx
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.
Persistent connections
Connection: keep-alive
asynchronous JavaScript and XML
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);
asynchronous JavaScript and XML
Pros:
- Less traffic
- Less load on server
- Quick interface
- Potentially better user experience
Cons:
- No default integration with default browser behavior
- Bad Search Engine support
- Project are harder
- JavaScript should be enabled in browser
- AJAX can be slow
- Security issues
JQUERY
$.ajax("https://example.com")
.success(function(data, textStatus, jqXHR){
//do something
}).error(function(jqXHR, textStatus, errorThrown){
//handle error
});
JQUERY
$.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
});
SUPERAGENT
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);
}
});
Cross-origin resource sharing
api.example.com
example.com/index.html
AJAX won't work
Cross-origin resource sharing
Cross-origin resource sharing
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
Cross-origin resource sharing
api.example.com
example.com/index.html
No cookies and some headers are missing
CORS
xhr.withCredentials = true;
Cross-origin resource sharing
XMLHttpRequest cannot load http://api.example.com. Origin http://api.bob.com is not allowed by Access-Control-Allow-Origin.
Thanks!
HTTP
By Alex Bardanov
HTTP
- 1,659