Skip to content

Instantly share code, notes, and snippets.

@jishanshaikh4
Forked from Fredkiss3/jsonfetch.ts
Created June 29, 2022 00:33
Show Gist options
  • Save jishanshaikh4/dbdb250bb8c58b6d9033214e8c0eadf5 to your computer and use it in GitHub Desktop.
Save jishanshaikh4/dbdb250bb8c58b6d9033214e8c0eadf5 to your computer and use it in GitHub Desktop.
JSON FETCH
async function jsonFetch<T>(
url: string,
options: RequestInit = {}
): Promise<T> {
// Set the default headers correctly
const headers: HeadersInit = new Headers(options.headers);
headers.set('Accept', 'application/json');
headers.set('Content-Type', 'application/json');
return fetch(url, {
...options,
headers,
credentials: 'include',
})
.then((response) => response.json())
.catch((error) => {
console.error('There was an error ?', error);
});
}
async function jsonFetch(url, options) {
// Set the default headers correctly
const headers: HeadersInit = new Headers(options.headers);
headers.set('Accept', 'application/json');
headers.set('Content-Type', 'application/json');
return fetch(url, {
...options,
headers,
credentials: 'include',
})
.then((response) => response.json())
.catch((error) => {
console.error('There was an error ?', error);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment