From 25eeae34ba229f4e0365d195d3b9a11a73c81340 Mon Sep 17 00:00:00 2001 From: Thomas Rubini <74205383+ThomasRubini@users.noreply.github.com> Date: Sun, 12 Mar 2023 12:56:04 +0100 Subject: [PATCH] allow makeAPIRequest() to handle JSON requests --- truthinquiry/static/js/api.js | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/truthinquiry/static/js/api.js b/truthinquiry/static/js/api.js index a573cfc..e242ab9 100644 --- a/truthinquiry/static/js/api.js +++ b/truthinquiry/static/js/api.js @@ -6,12 +6,22 @@ * @returns a Promise, which resolves when the server can be reached and responds without an error * and rejects otherwise */ -async function makeAPIRequest(endpoint, body) { +async function makeAPIRequest(endpoint, body, options={}) { + let fetchOptions = { + method: "POST", + headers: { + 'Accept': 'application/json' + } + }; + + if (options["content"] === 'json') { + fetchOptions["headers"]["Content-Type"] = 'application/json' + fetchOptions["body"] = JSON.stringify(body) + } else { + fetchOptions["body"] = new URLSearchParams(body); + } + return new Promise((resolve, reject) => { - const fetchOptions = { - method: "POST", - body: new URLSearchParams(body) - }; fetch("/api/v1/" + endpoint, fetchOptions).then(response => { const responseCode = response.status;