Created
December 9, 2020 17:49
-
-
Save wsanchez/8b75cc2932e85986627b1807e0ec8257 to your computer and use it in GitHub Desktop.
This file contains 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
_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