Skip to content

Instantly share code, notes, and snippets.

@wsanchez
Created December 9, 2020 17:49
Show Gist options
  • Save wsanchez/8b75cc2932e85986627b1807e0ec8257 to your computer and use it in GitHub Desktop.
Save wsanchez/8b75cc2932e85986627b1807e0ec8257 to your computer and use it in GitHub Desktop.
_fetchJSON = async (url, json=null, headers={}) => {
if (headers["Content-Type"] === undefined) {
headers["Content-Type"] = "application/json";
}
else if (headers["Content-Type"] !== "application/json") {
throw new Error(`Not JSON content-type: ${headers["Content-Type"]}`);
}
const requestHeaders = new Headers(headers);
const requestOptions = { mode: "no-cors", headers: requestHeaders }
if (json == null) {
requestOptions.method = "GET";
}
else {
requestOptions.method = "POST";
requestOptions.body = JSON.stringify(json);
}
console.log("****" + requestOptions.headers.get("content-type"));
// emits: application/json
const request = new Request(url, requestOptions);
console.log(">>>>" + request.headers.get("content-type"));
// emits: text/plain;charset=UTF-8
const response = await this._fetch(request);
const responseContentType = response.headers.get("Content-Type");
if (responseContentType !== "application/json") {
throw new Error(`Response type is not JSON: ${responseContentType}`);
}
return await response.json();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment