Skip to content

Instantly share code, notes, and snippets.

@mehrdadmg
Forked from vladilenm/JavaScript Fetch.js
Created February 21, 2021 13:28
Show Gist options
  • Save mehrdadmg/99bbdfcbd83b89d33325ec02719a2da2 to your computer and use it in GitHub Desktop.
Save mehrdadmg/99bbdfcbd83b89d33325ec02719a2da2 to your computer and use it in GitHub Desktop.

Revisions

  1. @vladilenm vladilenm revised this gist Oct 16, 2019. 2 changed files with 0 additions and 0 deletions.
    File renamed without changes.
    File renamed without changes.
  2. @vladilenm vladilenm created this gist Oct 16, 2019.
    38 changes: 38 additions & 0 deletions fetch.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    const requestURL = 'https://jsonplaceholder.typicode.com/users'

    function sendRequest(method, url, body = null) {
    const headers = {
    'Content-Type': 'application/json'
    }

    return fetch(url, {
    method: method,
    body: JSON.stringify(body),
    headers: headers
    }).then(response => {
    if (response.ok) {
    return response.json()
    }

    return response.json().then(error => {
    const e = new Error('Что-то пошло не так')
    e.data = error
    throw e
    })
    })
    }

    sendRequest('GET', requestURL)
    .then(data => console.log(data))
    .catch(err => console.log(err))

    const body = {
    name: 'Vladilen',
    age: 26
    }

    sendRequest('POST', requestURL, body)
    .then(data => console.log(data))
    .catch(err => console.log(err))


    41 changes: 41 additions & 0 deletions xhr.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    const requestURL = 'https://jsonplaceholder.typicode.com/users'

    function sendRequest(method, url, body = null) {
    return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()

    xhr.open(method, url)

    xhr.responseType = 'json'
    xhr.setRequestHeader('Content-Type', 'application/json')

    xhr.onload = () => {
    if (xhr.status >= 400) {
    reject(xhr.response)
    } else {
    resolve(xhr.response)
    }
    }

    xhr.onerror = () => {
    reject(xhr.response)
    }

    xhr.send(JSON.stringify(body))
    })
    }

    sendRequest('GET', requestURL)
    .then(data => console.log(data))
    .catch(err => console.log(err))

    const body = {
    name: 'Vladilen',
    age: 26
    }

    sendRequest('POST', requestURL, body)
    .then(data => console.log(data))
    .catch(err => console.log(err))