code.gitea.io/gitea@v1.21.7/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', headers = {}, data, body, ...other} = {}) {
    12    let contentType;
    13    if (!body) {
    14      if (data instanceof FormData || data instanceof URLSearchParams) {
    15        body = data;
    16      } else if (isObject(data) || Array.isArray(data)) {
    17        contentType = 'application/json';
    18        body = JSON.stringify(data);
    19      }
    20    }
    21  
    22    const headersMerged = new Headers({
    23      ...(!safeMethods.has(method.toUpperCase()) && {'x-csrf-token': csrfToken}),
    24      ...(contentType && {'content-type': contentType}),
    25    });
    26  
    27    for (const [name, value] of Object.entries(headers)) {
    28      headersMerged.set(name, value);
    29    }
    30  
    31    return fetch(url, {
    32      method,
    33      headers: headersMerged,
    34      ...(body && {body}),
    35      ...other,
    36    });
    37  }
    38  
    39  export const GET = (url, opts) => request(url, {method: 'GET', ...opts});
    40  export const POST = (url, opts) => request(url, {method: 'POST', ...opts});
    41  export const PATCH = (url, opts) => request(url, {method: 'PATCH', ...opts});
    42  export const PUT = (url, opts) => request(url, {method: 'PUT', ...opts});
    43  export const DELETE = (url, opts) => request(url, {method: 'DELETE', ...opts});