Created
April 18, 2018 16:10
-
-
Save jonurry/a002d723f307e697304de721d1b43f6f to your computer and use it in GitHub Desktop.
18.1 Content Negotiation (Eloquent JavaScript Solutions)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let aboutURL = 'https://eloquentjavascript.net/author'; | |
let mediaTypes = [ | |
'text/plain', | |
'text/html', | |
'application/json', | |
'application/rainbow+unicorns' | |
]; | |
async function getResponsesForMediaType(url, type) { | |
let r = await fetch(url, {headers: {'accept': type}}); | |
r = await r.text(); | |
console.log(`\n---------- type: ${type} ----------\n`, r); | |
}; | |
for (let type of mediaTypes) { | |
getResponsesForMediaType(aboutURL, type); | |
}; |
Hints
Base your code on the fetch
examples earlier in the chapter.
Asking for a bogus media type will return a response with code 406, “Not acceptable”, which is the code a server should return when it can’t fulfil the Accept
header.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
18.1 Content Negotiation
One of the things that HTTP can do is called content negotiation. The
Accept
request header is used to tell the server what type of document the client would like to get. Many servers ignore this header, but when a server knows of various ways to encode a resource, it can look at this header and send the one that the client prefers.The URL eloquentjavascript.net/author is configured to respond with either plaintext, HTML, or JSON, depending on what the client asks for. These formats are identified by the standardized media types
text/plain
,text/html
, andapplication/json
.Send requests to fetch all three formats of this resource. Use the
headers
property in the options object passed tofetch
to set the header namedAccept
to the desired media type.Finally, try asking for the media type
application/rainbows+unicorns
and see which status code that produces.