A small reusable API helper
One function for every call: JSON in, JSON out, one error format.
AJAX · A small reusable API helperIntermediate
async function api(path, { method = 'GET', body, headers = {} } = {}) {
const opts = { method, headers: { Accept: 'application/json', ...headers } };
if (body !== undefined) {
opts.headers['Content-Type'] = 'application/json';
opts.body = JSON.stringify(body);
}
const res = await fetch('/api' + path, opts);
const data = await res.json().catch(() => ({}));
if (!res.ok) {
const err = new Error(data.error || 'HTTP ' + res.status);
err.status = res.status;
err.data = data;
throw err;
}
return data;
}
api('/users', { method: 'POST', body: { name: 'Ali' } }).then(console.log);helperwrapperfetchjsonerrors