Networking in the Browser Module #36 Flashcards
What’s the “wrapper” that should enclose an API call when using Fetch or Axios?
(async ( ) => {
//FETCH or Axios statements about where to connect and what to do if a problem occurs
} )( )
Breaking down the above. Async is a function that is declared with the word async. Arguments/Params can be passed just as is possible with any function. Here we are using an arrow function so the name is omitted.
Add in the likely statements inside of the async function call.
1 (async ( ) => { 2 const response = await fetch('url') 3 const data = await response.json 4 } catch (error) { 5 console.error(error) } )( )
Explanation:
Line 1: opens the async function that wraps the call.
Line 2: “Go to this URL” & try to get a response code.
Line 3: Assign the returned object to a variable and try to get a JSON object as a response.
Line 4 if an error occurs catch it
Line 5 log the error to the console.
How is it possible to get more information about the API call you’re making?
By inspecting the returned headers. Therefor it is helpful to ask the API specifically for the information you seek. Example:
(async ( ) => {
try { const response = await fetch( ‘url’ )
console.log(‘response.headers.get(‘Content-Type’))
console.log(response.headers.get(‘Date’))
} catch(error) {
console.error(error)
}
})( )
What properties does the response object return?
method: GET, POST etc.
url: URL of the request
headers: the associated headers
referrer: the referrer of the request
cache: the cache mode of the req
How can you set the request headers and return the Headers object. (Hint: not the response headers, the Headers OBJ.)
By using a Headers constructor. See below:
const headers = new Headers( ) headers.append('Content-Type', 'application/json')
or:
const headers = new Headers( { 'Content-Type': 'application/json' } )
How to create a secure websockets connection?
const url = "wss://myserver.com/something" const connection = new WebSocket('url')