📎 Webclip
Make HTTP Requests with the Fetch API
The article says the Fetch API replaced the older XMLHttpRequest approach for client-side HTTP requests because it is promise-based and easier to use. It also introduces standardized Request and Response objects, along with related definitions for CORS and HTTP origin header semantics.
Reading notes#
- Fetch starts with
fetch, which takes a required resource path and can also receive an optionalinitobject. - The promise from
fetchresolves to aResponse, even when the HTTP status is 404 or 500; in those cases,okisfalse. fetchdoes not receive cross-site cookies, and it only sends cookies when thecredentialsoption is set.- A simple request can call
response.json()and then log the resulting JavaScript object. - The second argument can include
method,headers,body,mode,credentials,cache,redirect,referrer,referrerPolicy,integrity,keepalive, andsignal. - A POST request can send JSON in
bodyand setContent-typetoapplication/json; charset=UTF-8. - A file can be taken from a file input and sent in the request body, with the header adjusted to the server being used.
ResponseandBodyprovide methods such aserror,redirect,formData,json,text,arrayBuffer, andblob.- Useful response properties include
headers,ok,redirect,status,statusText,url, andbody. - The article concludes that Fetch is better than XMLHttpRequest because it handles many request types, supports text and binary bodies, and works well with other promises.
