Use Async Await, and Fetch in Node or Browsers

Here are some examples for REST API fetching for Node JS and browser. The REST API server example is based on Jsonplaceholder which provides a fake online REST API for testing and prototyping.

Node JS

We use request-promise for making request. First install the packages:

npm install --save request
npm install --save request-promise

Then run the script:

let rp = require('request-promise')
let options = {
method: 'GET',
uri: 'https://jsonplaceholder.typicode.com/posts',
json: true
}
rp(options)
.then(console.log)
.catch(console.log)

There are some configs in the options:

  • method: POST, GET, PUT, DELETE
  • uri: url or uri both work, but official documentation uses uri
  • json: set to true for automatically convert response to json format

Then use fetch-like syntax to get the data.


Browser

In browser we could use built-in function fetch to get the data.

let url = 'https://jsonplaceholder.typicode.com/posts'
let options = {
method: 'GET',
headers: new Headers({
'Content-Type': 'application/json'
})
}
async function reqListenerAsync (res) {
let data = await res.json()
console.log(data);
}
function reqError(err) {  
console.log('Fetch Error :'err)
}fetch(url, options)
.then(reqListenerAsync)
.catch(reqError)

We can either create Request object or split the url and other configs, here I choose the second method.

To create a Request object with configs:

let request = new Request('https://jsonplaceholder.typicode.com/posts', {
method: 'GET',
headers: new Headers({
'Content-Type': 'application/json'
})
})
fetch(request)
.then(functionHere)
.catch(errorHandlingHere)

With async, await and .json() features, so the .json() will return a promise that resolves with the result of JSON which was parsed from the body text, then set to data and console log it.

Fetch is supported by most of the modern browsers apart from IE.
Like what you read? Give Linuk a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.