Consuming a REST API as a client Module #67 Flashcards

1
Q

What are some of the things we need to think about in order to consume an api?

A
  1. How to connect

2. Which library to use: XHR, Fetch, Node https, Axios, or the request libraray.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is an XHR request comprised of?

A
  1. A variable with XMLhttprequest( ) assigned to it
  2. An event listener
  3. The variable for the item you’re requesting
  4. A for in loop
  5. The request
const xhr = new XMLHttpRequest()
xhr.addEventListener('readystatechange', function() {
  if (this.readyState === this.DONE) {
    const breeds = JSON.parse(this.responseText).message
    for (const breed in breeds) {
      console.log(breed)
    }
  }
})

xhr. open(‘GET’, ‘https://dog.ceo/api/breeds/list/all’)
xhr. send( )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the main ingredients for a fetch request?

A
  1. An async call
  2. a variable for the response and and await stating what we want and the method
  3. A data variable to recieve the data with JSON
  4. A for in loop
(async ( ) => {
  const response = await fetch('https://dog.ceo/api/breeds/list/all', {
    method: 'GET'
  })
  const data = await response.json()
  for (const breed in data.message) {
    console.log(breed)
  }
})( )
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What parts does the Node HTTPS Module have in it?

A
  1. A require statement that is assigned to a variable
  2. An options variable with a method, hostname, and path assignments
  3. The request assigned also to a variable with (options, res) callbacks
  4. A “chunks” variable assigned to an empty array
  5. A response handler with (data, chunk) callbacks that adds data to the empty array
  6. Another response handler to parse the JSON
  7. Disconnect method

const http = require(‘https’)

const options = {
  method: 'GET',
  hostname: 'dog.ceo',
  path: '/api/breeds/list/all',
}
const req = http.request(options, res => {
  const chunks = []

res.on(‘data’, chunk => {
chunks.push(chunk)
})

  res.on('end', () => {
    const body = Buffer.concat(chunks)
    const data = JSON.parse(body.toString())
    for (const breed in data.message) {
      console.log(breed)
    }
  })
})

req.end( )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What does the request library have in it’s requests?

A
  1. a request assigned to a variable
  2. an options varaiable with a method, url, json(true) assignments
  3. a request handler with options, error, response, and body callbacks
  4. a for in loop that loops through the a topic in the body
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Finally what parts does an Axios request have?

A
  1. Require the axios library
  2. an async/await function
  3. a for in loop that loops through a specified part of the response data
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What does the POST request from Axios look like?

A
  1. Require the Axios library
  2. async response/ await/ post function
    2a, Data
    2b. headers
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are a few of the advantages of Axios vs Fetch

A
  1. Supports older browsers
  2. Has a way to abort the request
  3. Has a way to set a response timeout
  4. built in CSRF protection
  5. Supports upload progress
  6. Transforms data to JSON automatically
  7. Works with node.js
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How can we install Axios?

A

npm install axios

or include it in an html page using unpkg

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Where does the https request start within axios

A

From the axios object:

axios({
  url: 'https://dog.ceo/api/breeds/list/all',
  method: 'get',
  data: {
    foo: 'bar'
  }
})
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are the two most common methods used in axios?

A

.post and .get (Just as in jQuery)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are the methods for the other HTTP verbs in axios?

A

axios. delete( )
axios. put( )
axios. patch( )
axios. options( )
axios. head( ) which is a method to get the HTTP headers and discard the body

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Here’s an example (again) of the Axios GET request with both async and promise based

A

PROMISE

const axios = require(‘axios’)

const getBreeds = async () => {
  try {
    return await axios.get('https://dog.ceo/api/breeds/list/all')
  } catch (error) {
    console.error(error)
  }
}
const countBreeds = async () => {
  const breeds = await getBreeds()

if (breeds.data.message) {
console.log(Got ${Object.entries(breeds.data.message).length} breeds)
}
}

countBreeds()

const axios = require(‘axios’)

const getBreeds = async () => {
  try {
    return await axios.get('https://dog.ceo/api/breeds/list/all')
  } catch (error) {
    console.error(error)
  }
}
const countBreeds = async () => {
  const breeds = await getBreeds()

if (breeds.data.message) {
console.log(Got ${Object.entries(breeds.data.message).length} breeds)
}
}

countBreeds()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How are parameters passed via URL in Axios?

A

By passing the url

axios.get(‘https://site.com/?foo=bar’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How are arguments passed in a POST request as a second parameter (Axios)

A

By passing the url first and then passing the parameter in the next line
axios.post(‘https://site.com/’, {
foo: ‘bar’
})

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

If you try to connect to a server via JavaScript from outside of a domain, what happens?

A

It gets terminated by the Cross-Origin Resource Sharing policy built-in to the browser.

17
Q

Using Express, how is the CORS middleware package used?

A

Make sure to visit https://github.com/expressjs/cors to get the cors package.

const express = require("express")
const cors = require("cors")
const app = express()

app.get(“/with-cors”, cors(), (req, res, next) => {
res.json({ msg: “WHOAH with CORS it works! 🔝 🎉” })
})

/* the rest of the app */

18
Q

Here’s a simple example of the cors package in use

A

This is the Node.js Express server: https://glitch.com/edit/#!/flaviocopes-cors-example-express

document.addEventListener(‘DOMContentLoaded’, () => {

  const requests = [
    { 
      url: 'https://flaviocopes-cors-example-express.glitch.me/without-cors',
      container: 'response-one'
    }, { 
      url: 'https://flaviocopes-cors-example-express.glitch.me/with-cors',
      container: 'response-two'
    }
  ]

for (const request of requests) {
fetch(request.url)
.then((response) => {
response.json().then((data) => {
document.getElementById(request.container)
.getElementsByTagName(‘p’)[0]
.innerHTML = data.msg
})
})
.catch((err) => {
document.getElementById(request.container)
.getElementsByTagName(‘p’)[0]
.innerHTML = ‘CORS Error! 😯’
})
}

}, false);

19
Q

What do you need to do to prevent others from serving your endpoint(s)?

A

The CORS response header

You need to configure the server to only allow one origin to serve, and block all the others.

Using the same cors Node library, here’s how you would do it:

const cors = require(“cors”)

const corsOptions = {
  origin: "https://yourdomain.com",
}
app.get("/products/:id", cors(corsOptions), (req, res, next) => {
  //...
})
20
Q

How can you allow multiple domains to serve your endpoints?

A

Just white list those domains as below:

const whitelist = ["http://example1.com", "http://example2.com"]
const corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error("Not allowed by CORS"))
    }
  },
}
21
Q

Some requests go through a preflight in order to check permissions. How do we set up the call to allow for options?

A
const express = require("express")
const cors = require("cors")
const app = express()
//allow OPTIONS on just one resource
app.options("/the/resource/you/request", cors())
//allow OPTIONS on all resources
app.options("*", cors())