| 11 | } |
| 12 | |
| 13 | export async function fetchPostJSON(url: string, data?: {}) { |
| 14 | try { |
| 15 | // Default options are marked with * |
| 16 | const response = await fetch(url, { |
| 17 | method: "POST", // *GET, POST, PUT, DELETE, etc. |
| 18 | mode: "cors", // no-cors, *cors, same-origin |
| 19 | cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached |
| 20 | credentials: "same-origin", // include, *same-origin, omit |
| 21 | headers: { |
| 22 | "Content-Type": "application/json", |
| 23 | // 'Content-Type': 'application/x-www-form-urlencoded', |
| 24 | }, |
| 25 | redirect: "follow", // manual, *follow, error |
| 26 | referrerPolicy: "no-referrer", // no-referrer, *client |
| 27 | body: JSON.stringify(data || {}), // body data type must match "Content-Type" header |
| 28 | }); |
| 29 | return await response.json(); // parses JSON response into native JavaScript objects |
| 30 | } catch (err) { |
| 31 | if (err instanceof Error) { |
| 32 | throw new Error(err.message); |
| 33 | } |
| 34 | throw err; |
| 35 | } |
| 36 | } |