code.gitea.io/gitea@v1.22.3/web_src/js/modules/fetch.js (about) 1 import {isObject} from '../utils.js'; 2 3 const {csrfToken} = window.config; 4 5 // safe HTTP methods that don't need a csrf token 6 const safeMethods = new Set(['GET', 'HEAD', 'OPTIONS', 'TRACE']); 7 8 // fetch wrapper, use below method name functions and the `data` option to pass in data 9 // which will automatically set an appropriate headers. For json content, only object 10 // and array types are currently supported. 11 export function request(url, {method = 'GET', data, headers = {}, ...other} = {}) { 12 let body, contentType; 13 if (data instanceof FormData || data instanceof URLSearchParams) { 14 body = data; 15 } else if (isObject(data) || Array.isArray(data)) { 16 contentType = 'application/json'; 17 body = JSON.stringify(data); 18 } 19 20 const headersMerged = new Headers({ 21 ...(!safeMethods.has(method) && {'x-csrf-token': csrfToken}), 22 ...(contentType && {'content-type': contentType}), 23 }); 24 25 for (const [name, value] of Object.entries(headers)) { 26 headersMerged.set(name, value); 27 } 28 29 return fetch(url, { 30 method, 31 headers: headersMerged, 32 ...other, 33 ...(body && {body}), 34 }); 35 } 36 37 export const GET = (url, opts) => request(url, {method: 'GET', ...opts}); 38 export const POST = (url, opts) => request(url, {method: 'POST', ...opts}); 39 export const PATCH = (url, opts) => request(url, {method: 'PATCH', ...opts}); 40 export const PUT = (url, opts) => request(url, {method: 'PUT', ...opts}); 41 export const DELETE = (url, opts) => request(url, {method: 'DELETE', ...opts});