Networking in the Browser Module #36 Flashcards

1
Q

What’s the “wrapper” that should enclose an API call when using Fetch or Axios?

A

(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.

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

Add in the likely statements inside of the async function call.

A
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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How is it possible to get more information about the API call you’re making?

A

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)
}
})( )

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

What properties does the response object return?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How can you set the request headers and return the Headers object. (Hint: not the response headers, the Headers OBJ.)

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How to create a secure websockets connection?

A
const url = "wss://myserver.com/something"
const connection = new WebSocket('url')
How well did you know this?
1
Not at all
2
3
4
5
Perfectly