Last active
March 1, 2024 02:28
-
-
Save vladilenm/55757c96182d8d03678aa32b7354fe85 to your computer and use it in GitHub Desktop.
JavaScript Fetch + XMLHttpRequest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
it doesn't work (