Skip to content

Commit

Permalink
fix(api.js): update how api.js add header/body and update apitest to …
Browse files Browse the repository at this point in the history
…use existing func
  • Loading branch information
junglesub committed Aug 1, 2024
1 parent 0ff3e80 commit 81b534e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 22 deletions.
15 changes: 3 additions & 12 deletions src/pages/ApiTest.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { useRecoilValue } from "recoil";
import { authJwtAtom } from "../recoil/auth/atoms";
import styled from "styled-components";
import { serverRootUrl } from "../constants";
import { fetchBe } from "../tools/api";

const presets = [
{
Expand Down Expand Up @@ -126,18 +127,8 @@ function ApiTest() {
};

const sendApiRequest = () => {
fetch(serverRootUrl + targetEndPoint, {
method: requestType,
headers: {
Authorization: jwtValue ? `Bearer ${jwtValue}` : undefined,
"Content-Type": "application/json",
},
body:
requestType !== "GET"
? JSON.stringify(JSON.parse(requestData))
: undefined,
})
.then((data) => data.json().then((json) => setResponseData(json)))
fetchBe(jwtValue, targetEndPoint, requestType, requestData)
.then((json) => setResponseData(json))
.catch((e) => setResponseData(e.message));
};
return (
Expand Down
26 changes: 16 additions & 10 deletions src/tools/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,24 @@ import { serverRootUrl } from "../constants";

export const fetchBe = (jwtValue, path, method = "GET", body) =>
new Promise((res, rej) => {
fetch(serverRootUrl + path, {
headers: {
Authorization: `Bearer ${jwtValue}`,
"Content-Type": body ? "application/json" : undefined,
},
method: method,
body: body ? JSON.stringify(body) : undefined,
})
.then((data) =>
data.json().then((json) => {
const initStuff = {
headers: {},
method,
};
if (body && !["GET", "HEAD"].includes(method)) {
initStuff.headers["Content-Type"] = "application/json";
initStuff["body"] = body;
}
if (jwtValue) initStuff.headers.Authorization = `Bearer ${jwtValue}`;

console.log(body);

fetch(serverRootUrl + path, initStuff)
.then((doc) =>
doc.json().then((json) => {
res(json);
})
)

.catch((err) => rej(err));
});

0 comments on commit 81b534e

Please sign in to comment.