# Uploading and Receiving Data
There are several ways that we can attach data to a fetch request.
# Request Object
When calling the fetch( )
method we can either pass in just a URL or a Request Object.
To create a Request
Object we would use the new Request( )
constructor. The most basic example, using all default properties is:
let req = new Request(url);
You can also optionally add an init object with values for the various properties of the Request.
let req = new Request(url, { method: 'POST', body: myFormData });
The properties of the Request can include:
method: 'GET', 'POST', 'PUT', 'DELETE' or 'HEAD'
headers: a Headers object
mode: 'cors' or 'no-cors' (Cross-Origin Resource Sharing), or 'same-origin'.
cache: 'default', 'no-store', 'reload', 'no-cache', or 'force-cache' - the cache mode to use for the request.
body: The data to be sent with a request that is using method: 'POST'. This property can be a Blob, a USVString, an Array Buffer, a FormData object, or a URLSearchParams object. FormData and Blob are the most common to use.
2
3
4
5
# QueryStrings
The QueryString is part of the URL that we would pass to the server. It begins with a question mark.
http://www.example.com/folder/file.php?keyword=CSS&limit=50
Above is an example URL that includes a querystring. It starts with a ?
and then is followed by two name value pairs. The name and value of each property is an equal sign. Between each name-value pair is an ampersand.
This is the simpliest way to pass values. This approach is available for any of the request methods - POST, GET, DELETE, etc. The querystring is actually one of the headers. (see below for more details on headers).
# The FormData Object
When making AJAX calls to an API, we often need to send additional data as part of the request. The data we send can take many forms, including querystrings or form data.
QueryStrings can always be passed as part of the URL and just handled as a String. Data that you gather can also be packaged inside a FormData object.
When you want to send data to your API call packaged in either a QueryString then you will likely use the GET method. If you use a FormData object then we MUST use the POST method. If you keep the querystring as a String and just part of the URL then we can use the GET method or the POST method.
The FormData object stores data as name - value pairs.
Let's start with a name and email address pulled from a web form.
let name = document.getElementById('name').value;
let email = document.getElementById('email').value;
2
Then we store the data in one of the following ways.
In a FormData object:
let form = new FormData();
form.append('name', name);
form.append('email', email);
2
3
Then we place the data in a Request object and send it with our fetch call:
let url = "http://www.example.com/";
let req = new Request(url, {
method: "POST",
body: form
});
fetch(req)
.then( function(response){
return response.json();
})
.then( data ){
//data is our JSON object back from our request
});
2
3
4
5
6
7
8
9
10
11
12
13
# Headers
The Header Object represents all the HTTP headers in both the Request and the Response.
It can be passed as a value to the Request init property:
let myHeaders = new Header();
myHeaders.append('Accept', 'image/jpeg');
let url = 'someImage.jpg';
let req = new Request(url, { headers: myHeaders });
2
3
4
It is important to keep in mind that while you can create your own headers, there is a list of headers which are read-only and the browsers will not allow you to set values for them.
List of Forbidden Header names
# Body Object
When using the POST method, all the data that is not in the Header
will be inside the Body
object. FormData is one way of adding content to the body. However, you can also put raw data in the Body
.
Use the network tab in the Chrome Dev tools to investigate the data being sent through the Body with any request.
When a response comes back from the Server, it will most likely contain data inside the Body
of the Response
. The Body
has several methods that allow us to extract the expected content from the body.
Body.json(); //used to extract the JSON representation from a JSON file in the response
Body.text(); //used to extract the string version of an XML, HTML, or other text file.
Body.blob(); //used to extract the image from the response body
2
3
4
5
# Response Object
When your fetch Request returns from the Server you will have a Response
object. It is the last part of the fetch process is handling the Response. Just like the Request, it can contain Headers as well as the Body.
When you call the fetch
method, the first then( )
function will receive the Request
object as it's only parameter. From that function you can call the json( )
, blob( )
, or text( )
method to extract the desired data from the Response Body.
fetch(url)
.then(function(resp) {
//extract the JSON Object from the returned file
return resp.json();
})
.then(function(data) {
//the variable data will contain the JSON data from the returned file.
})
.catch(function(err) {
//handle any errors
});
2
3
4
5
6
7
8
9
10
11
In the example, above, the variable resp
is a Response
object. Here are the methods that you would call in that first then( )
function.
Response.json(); //if your returned file was a .json file.
Response.text(); //if you were expecting HTML, XML, text, or CSV
Response.blob(); //if you were expecting a binary file like an image, video, or audio.
2
3
4
5
The data
variable in the second then()
is the result of calling the json()
method. These three methods are actually being inherited from the Body
object.