mihawk
Version:
A tiny & simple mock server tool, support json,js,cjs,ts(typescript).
33 lines (32 loc) • 1.21 kB
JavaScript
export async function jsonRequest(url, options) {
const isHttps = url.startsWith('https://');
options = formatOptions(options, isHttps);
const apiRes = await fetch(url, {
...options,
headers: {
...options?.headers,
'Content-Type': 'application/json',
Cookie: options.headers.Cookie,
},
});
const resContentType = apiRes.headers.get('content-type') || apiRes.headers.get('Content-Type') || '';
if (!resContentType || (!resContentType.includes('application/json') && !resContentType.includes('json') && !resContentType.includes('text'))) {
throw new Error(`Invalid content-type: ${resContentType || 'unknown'}`);
}
const res = await apiRes.json();
return res;
}
function formatOptions(options, isHttps) {
options = options || {};
options.method = (options.method || 'GET');
if (['HEAD', 'GET'].includes(options.method.toUpperCase())) {
delete options.body;
}
if (options.headers?.['Content-Length']) {
delete options.headers['Content-Length'];
}
if (options.headers?.['content-length']) {
delete options.headers['content-length'];
}
return options;
}