Learn JavaScript - Requests Cheatsheet - Codecademy

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Cheatsheets / Learn JavaScript

Requests
Asynchronous calls with XMLHttpRequest
AJAX enables HTTP requests to be made not only
during the load time of a web page but also anytime const xhr = new XMLHttpRequest();
after a page initially loads. This allows adding dynamic xhr.open('GET',
behavior to a webpage. This is essential for giving a 'mysite.com/api/getjson');
good user experience without reloading the webpage
for transferring data to and from the web server.
The XMLHttpRequest (XHR) web API provides the ability
to make the actual asynchronous request and uses
AJAX to handle the data from the request.
The given code block is a basic example of how an
HTTP GET request is made to the specified URL.

HTTP POST request


HTTP POST requests are made with the intention of
sending new information to the source (server) that will
receive it.
For a POST request, the new information is stored in
the body of the request.

HTTP GET request


HTTP GET requests are made with the intention of
retrieving information or data from a source (server)
over the web.
GET requests have no body, so the information that
the source requires, in order to return the proper
response, must be included in the request URL path or
query string.

The query string in a URL


Query strings are used to send additional information
to the server during an HTTP GET request. const requestUrl
The query string is separated from the original URL = 'http://mysite.com/api/vendor?
using the question mark character ? . name=kavin&id=35412';
In a query string, there can be one or more key-value
pairs joined by the equal character = .
For separating multiple key-value pairs, an ampersand
character & is used.
Query strings should be url-encoded in case of the
presence of URL unsafe characters.
JSON: JavaScript Object Notation
JSON or JavaScript Object Notation is a data format
suitable for transporting data to and from a server. const jsonObj = {
It is essentially a slightly stricter version of a Javascript   "name": "Rick",
object. A JSON object should be enclosed in curly   "id": "11A",
braces and may contain one or more property-value   "level": 4  
pairs. JSON names require double quotes, while
};
standard Javascript objects do not.

XMLHttpRequest GET Request Requirements


The request type, response type, request URL, and
handler for the response data must be provided in const req = new XMLHttpRequest();
order to make an HTTP GET request with the JavaScript req.responseType = 'json';
XMLHttpRequest API. req.open('GET', '/myendpoint/getdata?
The URL may contain additional data in the query
id=65');
string. For an HTTP GET request, the request type must
req.onload = () => {
be GET .
  console.log(req.response);
};

req.send();

HTTP POST request with the XMLHttpRequest API


To make an HTTP POST request with the JavaScript
XMLHttpRequest API, a request type, response type, const data = {
request URL, request body, and handler for the   fish: 'Salmon',
response data must be provided. The request body is   weight: '1.5 KG',
essential because the information sent via the POST   units: 5
method is not visible in the URL. The request type must
};
be POST for this case. The response type can be a
const xhr = new XMLHttpRequest();
variety of types including array buffer, json, etc.
xhr.open('POST', '/inventory/add');
xhr.responseType = 'json';
xhr.send(JSON.stringify(data));

xhr.onload = () => {


  console.log(xhr.response);
};
ok property fetch api
In a Fetch API function fetch() the ok property of a
response checks to see if it evaluates to true or     fetch(url, {
false . In the code example the .ok property will be     method: 'POST',
true when the HTTP request is successful. The .ok     headers: {
property will be false when the HTTP request is       'Content-type': 'application/json',
unsuccessful.
      'apikey': apiKey
    },
    body: data
  }).then(response => {
    if (response.ok) {
      return response.json();
    }
    throw new Error('Request failed!');
  }, networkError => {
    console.log(networkError.message)
  })
}

JSON Formatted response body


The .json() method will resolve a returned promise to
a JSON object, parsing the body text as JSON. fetch('url-that-returns-JSON')
The example block of code shows .json() method .then(response => response.json())
that returns a promise that resolves to a JSON- .then(jsonResponse => {
formatted response body as a JavaScript object.   console.log(jsonResponse);
});

promise url parameter fetch api


A JavaScript Fetch API is used to access and
manipulate requests and responses within the HTTP fetch('url')
pipeline, fetching resources asynchronously across a .then(
network.   response  => {
A basic fetch() request will accept a URL parameter,     console.log(response);
send a request and contain a success and failure
  },
promise handler function.
rejection => {
In the example, the block of code begins by calling the
    console.error(rejection.message);
fetch() function. Then a then() method is chained
to the end of the fetch() . It ends with the response );
callback to handle success and the rejection callback
to handle failure.
Fetch API Function
The Fetch API function fetch() can be used to create
requests. Though accepting additional arguments, the fetch('https://api-to-call.com/endpoint',
request can be customized. This can be used to change {
the request type, headers, specify a request body, and   method: 'POST',
much more as shown in the example block of code.
body: JSON.stringify({id: "200"})
}).then(response => {
  if(response.ok){
      return response.json();  
  }
    throw new Error('Request failed!');
}, networkError => {
  console.log(networkError.message);
}).then(jsonResponse => {
  console.log(jsonResponse);
})

async await syntax


The async…await syntax is used with the JS Fetch API
fetch() to work with promises. In the code block const getSuggestions = async () => {
example we see the keyword async placed the   const wordQuery = inputField.value;
function. This means that the function will return a   const endpoint
promise. The keyword await makes the JavaScript
= `${url}${queryParams}${wordQuery}`;
wait until the problem is resolved.
  try{
const response = __~await~__
__~fetch(endpoint, {cache: 'no-cache'});
    if(response.ok){
      const jsonResponse = await
response.json()
    }
  }
  catch(error){
    console.log(error)
  }
}

You might also like