Javascript Network Request

Fetch API

The Fetch API is a modern interface that allows you to make HTTP requests to servers from web browsers. The Fetch API is much simpler and cleaner. It uses the promise  to deliver more flexible features to make requests to servers from the web browsers. The fetch() method is available in the global scope that instructs the web browsers to send a request to a URL. You don’t have to install any library. 

Syntax

let promise = fetch(url, [options]);

Without options that is a simple GET request, downloading the contents of the url. The browser starts the request right away and returns a promise that the calling code should use to get the result.

POST Request

method – set to POST

body – the request body, one of following goes in the options.

    • a string (e.g. JSON-encoded)
    • Formdata object, to submit the data as form/multipart
    • Blob / BufferSource to send binary data

The JSON format is used most of the time.

let headers = {
    "Content-Type": "application/json",
    "x-api-key":"lovemesomecoding"
};
let user = {
    firstName: 'Folau',
    lastName: 'Kaveinga',
    email: 'folaukaveinga@gmail.com'
};

let options = {};
options.method = "POST";
options.body = JSON.stringify(user);
options.headers = headers;

let url = "http://localhost:8888/users/signup";

let response = await fetch(url, options);

if (response.ok) { // if HTTP-status is 200-299
    let data = await response.json();

    let content = "";
    content += "id: "+data.id+"<br>";
    content += "firstName: "+data.firstName+"<br>";
    content += "lastName: "+data.lastName+"<br>";
    content += "email: "+data.email+"<br>";

    document.getElementById("signUpContent").innerHTML = content;
    document.getElementById("errorMsg").innerHTML = "";
} else {
    let error = await response.json();
    console.log(error);
    document.getElementById("errorMsg").innerHTML = error.message;
}

GET Request

let headers = {
    "Content-Type": "application/json",
    "token":"lovemesomecoding-token"
};

let options = {};
options.method = "GET";
options.headers = headers;

let id = 1;

let url = "http://localhost:8888/users/"+id;

let response = await fetch(url, options);

if (response.ok) { // if HTTP-status is 200-299
    let data = await response.json();

    let content = "";
    content += "id: "+data.id+"<br>";
    content += "firstName: "+data.firstName+"<br>";
    content += "lastName: "+data.lastName+"<br>";
    content += "email: "+data.email+"<br>";

    document.getElementById("getUserContent").innerHTML = content;
    document.getElementById("errorMsg").innerHTML = "";
} else {
    let error = await response.json();
    console.log(error);
    document.getElementById("errorMsg").innerHTML = error.message;
}

PUT Request

let headers = {
    "Content-Type": "application/json",
    "token":"lovemesomecoding"
};
let user = {
    firstName: 'Folau',
    lastName: 'Kaveinga',
    email: 'folaukaveinga@gmail.com',
    id: 1
};

let options = {};
options.method = "PUT";
options.body = JSON.stringify(user);
options.headers = headers;

let url = "http://localhost:8888/users";

let response = await fetch(url, options);
//console.log(response);

if (response.ok) { // if HTTP-status is 200-299
    let data = await response.json();

    let content = "";
    content += "id: "+data.id+"<br>";
    content += "firstName: "+data.firstName+"<br>";
    content += "lastName: "+data.lastName+"<br>";
    content += "email: "+data.email+"<br>";

    document.getElementById("updateUserContent").innerHTML = content;
    document.getElementById("errorMsg").innerHTML = "";
} else {
    let error = await response.json();
    console.log(error);
    document.getElementById("errorMsg").innerHTML = error.message;
}

Upload File

Upload File
<br>
<div class="form-group">
    <label for="exampleFormControlFile1">file input</label>
    <input type="file" class="form-control-file" id="uploadingFile">
</div>
<button onclick="uploadFile()" type="button" class="btn btn-outline-primary">Upload File</button>
const formData = new FormData();
const fileField = document.getElementById("uploadingFile");
formData.append('file', fileField.files[0]);

let headers = {
    "token":"lovemesomecoding"
};

let options = {};
options.method = "POST";
options.body = formData;
options.headers = headers;

let url = "http://localhost:8888/users/document";

let response = await fetch(url, options);

if (response.ok) { // if HTTP-status is 200-299
    let data = await response.json();

    document.getElementById("uploadFileStatus").innerHTML = "uploaded: "+data;
    document.getElementById("errorMsg").innerHTML = "";
} else {
    let error = await response.json();
    console.log(error);
    document.getElementById("errorMsg").innerHTML = error.message;
}

Upload Multiple Files

Upload Files
<br>
<div class="form-group">
    <label for="exampleFormControlFile1">files input</label>
    <input type="file" class="form-control-file" id="uploadingFiles" multiple>
</div>
<button onclick="uploadFiles()" type="button" class="btn btn-outline-primary">Upload Files</button>
const formData = new FormData();
const fileField = document.getElementById("uploadingFiles");

for (let i = 0; i < fileField.files.length; i++) {
    formData.append('files', fileField.files[i]);
}

let headers = {
    "token":"lovemesomecoding"
};

let options = {};
options.method = "POST";
options.body = formData;
options.headers = headers;

let url = "http://localhost:8888/users/documents";

let response = await fetch(url, options);

if (response.ok) { // if HTTP-status is 200-299
    let data = await response.json();

    document.getElementById("uploadFileStatus").innerHTML = "uploaded: "+data;
    document.getElementById("errorMsg").innerHTML = "";

} else {
    let error = await response.json();
    console.log(error);
    document.getElementById("errorMsg").innerHTML = error.message;
}

Fetch source code on Github

Axios API

Install axios via npm

npm install axios

CDN script

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Create an instance of Axios

const axiosInstance = axios.create({
    baseURL: 'http://localhost:8888',
    timeout: 1000,
    headers: {
        "Content-type": "application/json",
        "token": "foobar"
    }
});

POST Request

let headers = {
    "x-api-key":"lovemesomecoding"
};
let user = {
    firstName: 'Folau',
    lastName: 'Kaveinga',
    email: 'folaukaveinga@gmail.com'
};

let options = {};
options.method = "POST";
options.data = JSON.stringify(user);
options.headers = headers;

let url = "/users/signup";

let response = await axiosInstance(url, options);

console.log(response);

if (response.status >= 200) { 
    let data = await response.data;

    let content = "";
    content += "id: "+data.id+"<br>";
    content += "firstName: "+data.firstName+"<br>";
    content += "lastName: "+data.lastName+"<br>";
    content += "email: "+data.email+"<br>";

    document.getElementById("signUpContent").innerHTML = content;
    document.getElementById("errorMsg").innerHTML = "";
} else {
    let error = await response.json();
    console.log(error);
    document.getElementById("errorMsg").innerHTML = error.message;
}

 

GET Request

let headers = {
    "token":"lovemesomecoding-token"
};

let options = {};
options.method = "GET";
options.headers = headers;

let id = 1;

let url = "/users/"+id;

let response = await axiosInstance(url, options);

if (response.status >= 200) { 
    let data = await response.data;

    let content = "";
    content += "id: "+data.id+"<br>";
    content += "firstName: "+data.firstName+"<br>";
    content += "lastName: "+data.lastName+"<br>";
    content += "email: "+data.email+"<br>";

    document.getElementById("getUserContent").innerHTML = content;
    document.getElementById("errorMsg").innerHTML = "";
} else {
    let error = await response.data;
    console.log(error);
    document.getElementById("errorMsg").innerHTML = error.message;
}

 

PUT Request

let headers = {
    "token":"lovemesomecoding"
};
let user = {
    firstName: 'Folau',
    lastName: 'Kaveinga',
    email: 'folaukaveinga@gmail.com',
    id: 1
};

let options = {};
options.method = "PUT";
options.body = JSON.stringify(user);
options.headers = headers;

let url = "/users";

let response = await axiosInstance(url, options);
//console.log(response);

if (response.status >= 200) { 
    let data = await response.data;

    let content = "";
    content += "id: "+data.id+"<br>";
    content += "firstName: "+data.firstName+"<br>";
    content += "lastName: "+data.lastName+"<br>";
    content += "email: "+data.email+"<br>";

    document.getElementById("updateUserContent").innerHTML = content;
    document.getElementById("errorMsg").innerHTML = "";
} else {
    let error = await response.data;
    console.log(error);
    document.getElementById("errorMsg").innerHTML = error.message;
}

 

Upload File

const formData = new FormData();
const fileField = document.getElementById("uploadingFile");
formData.append('file', fileField.files[0]);

let headers = {
    "token":"lovemesomecoding",
    "Content-Type": "multipart/form-data"
};

let options = {
    // `onUploadProgress` allows handling of progress events for uploads
    // browser only
    onUploadProgress: function (progressEvent) {
        console.log("progressEvent");
        console.log(progressEvent);
    },
    // `onDownloadProgress` allows handling of progress events for downloads
    // browser only
    onDownloadProgress: function (progressEvent) {
        console.log("progressEvent");
        console.log(progressEvent);
    }
};
options.headers = headers;

let url = "/users/document";

let response = await axiosInstance.post(url, formData, options);

console.log(response);

if (response.status >= 200) { 
    let data = await response.data;

    document.getElementById("uploadFileStatus").innerHTML = "uploaded: "+data.finishUpload;
    document.getElementById("errorMsg").innerHTML = "";
} else {
    let error = await response.json();
    console.log(error);
    document.getElementById("errorMsg").innerHTML = error.message;
}

Upload Multiple Files

const formData = new FormData();
const fileField = document.getElementById("uploadingFiles");

for (let i = 0; i < fileField.files.length; i++) {
    formData.append('files', fileField.files[i]);
}

let headers = {
    "token":"lovemesomecoding",
    "Content-Type":"multipart/form-data"
};

let options = {
    // `onUploadProgress` allows handling of progress events for uploads
    // browser only
    onUploadProgress: function (progressEvent) {
        console.log("progressEvent");
        console.log(progressEvent);
    },
    // `onDownloadProgress` allows handling of progress events for downloads
    // browser only
    onDownloadProgress: function (progressEvent) {
        console.log("progressEvent");
        console.log(progressEvent);
    }
};

options.headers = headers;

let url = "/users/documents";

let response = await axiosInstance.post(url, formData, options);

if (response.status >= 200) { 
    let data = await response.data;

    document.getElementById("uploadFileStatus").innerHTML = "uploaded: "+data.finishUpload;
    document.getElementById("errorMsg").innerHTML = "";

} else {
    let error = await response.json();
    console.log(error);
    document.getElementById("errorMsg").innerHTML = error.message;
}

 

Axios source code on Github




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *