DEV Community

Cover image for How to Use Fetch to make Ajax calls in JavaScript

Posted on

How to Use Fetch to make Ajax calls in JavaScript

Fetch is an interface to make requests and responses from a backend to frontend.

The requests are sent as GET by default.To send POST/PATCH/DELETE/PUT you can use a method property as part of options it can take values such as:

MODE: SUCH AS CORS, NO-CORS, SAME ORIGIN(depends on your browser)


postUser = body => fetch(this.usersURL, {
method: "POST",
headers: this.headers,
body: JSON.stringify(body)

There’s an umbrella called AJAX(Asynchronous Javascript and Xml)
Using Ajax and Fetch IS flexible and easy to use because of its syntax and structure, it’s supported by modern browsers and ES6 Javascript(so make sure to read the requirements)

Some definitions I think are useful to share are:

XML: Lets you convert data to JSON to your device.

JSON: JavaScript Object Notation is a syntax to serializing objects, arrays, numbers, strings, booleans and NULL

Calling Fetch returns a promise for example:

fetchScores = () => fetch(this.scoresURL).then(this.parseJSON)

Some methods you should know are:
JSON(): Resolves the promise

CLONE(): Creates a clone of the response

arrayBuffer(): Returns a promise that resolves with a generic fixed length raw binary data buffer(temporarily stores data while it is being moved from one place to another)


Javascript fetch request-responses are used to make asynchronous HTTP requests, using as much clearer code and delivering flexible features to make requests to servers from web browsers.

Thanks for reading!

Discussion (0)