Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
const BASE = "https://api.example.com"; async function api(path, opts = {}) { const headers = { "Content-Type": "application/json", ...opts.headers }; const token = localStorage.getItem("token"); if (token) headers.Authorization = `Bearer ${token}`; const res = await fetch(BASE + path, { ...opts, headers }); if (res.status === 401) { logout(); return; } if (!res.ok) throw new Error(`HTTP ${res.status}`); return res.json(); } export const get = (path) => api(path); export const post = (path, body) => api(path, { method: "POST", body: JSON.stringify(body) });
Result
Open