What are some of the things we need to think about in order to consume an api?
2. Which library to use: XHR, Fetch, Node https, Axios, or the request libraray.
What is an XHR request comprised of?
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( )
What are the main ingredients for a fetch request?
(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)
}
})( )What parts does the Node HTTPS Module have in it?
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( )
What does the request library have in it’s requests?
Finally what parts does an Axios request have?
What does the POST request from Axios look like?
What are a few of the advantages of Axios vs Fetch
How can we install Axios?
npm install axios
or include it in an html page using unpkg
Where does the https request start within axios
From the axios object:
axios({
url: 'https://dog.ceo/api/breeds/list/all',
method: 'get',
data: {
foo: 'bar'
}
})What are the two most common methods used in axios?
.post and .get (Just as in jQuery)
What are the methods for the other HTTP verbs in axios?
axios. delete( )
axios. put( )
axios. patch( )
axios. options( )
axios. head( ) which is a method to get the HTTP headers and discard the body
Here’s an example (again) of the Axios GET request with both async and promise based
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 are parameters passed via URL in Axios?
By passing the url
axios.get(‘https://site.com/?foo=bar’)
How are arguments passed in a POST request as a second parameter (Axios)
By passing the url first and then passing the parameter in the next line
axios.post(‘https://site.com/’, {
foo: ‘bar’
})
If you try to connect to a server via JavaScript from outside of a domain, what happens?
It gets terminated by the Cross-Origin Resource Sharing policy built-in to the browser.
Using Express, how is the CORS middleware package used?
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 */
Here’s a simple example of the cors package in use
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);
What do you need to do to prevent others from serving your endpoint(s)?
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) => {
//...
})How can you allow multiple domains to serve your endpoints?
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"))
}
},
}Some requests go through a preflight in order to check permissions. How do we set up the call to allow for options?
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())