Skip to content

Instantly share code, notes, and snippets.

@MiCkEyZzZ
Last active June 3, 2021 11:43
Show Gist options
  • Save MiCkEyZzZ/5c44df2fdc51172aef88dc595be065ee to your computer and use it in GitHub Desktop.
Save MiCkEyZzZ/5c44df2fdc51172aef88dc595be065ee to your computer and use it in GitHub Desktop.
const URL = "https://jsonplaceholder.typicode.com/users"
class Http {
get(url, headers) {
return makeRequest('GET', url, headers)
}
post(url, headers, body) {
return makeRequest('POST', url, headers, body)
}
}
const http = new Http()
function makeRequest(method, url, body) {
const headers = {
'Content-Type': 'application/json'
}
return fetch(url, {
method,
headers,
body: JSON.stringify(body)
}).then(response => {
if (response.ok) {
return response.json()
}
return response.json().then(error => {
const e = new Error('Something went wrong!')
e.data = error
throw e
})
})
}
class User {
constructor(name, password) {
this.name = name
this.password = password
}
}
const user = new User('Mikhail', '123456')
http.post(URL, user)
.then(data => console.log(data))
.catch(err => console.log(err))
@MiCkEyZzZ
Copy link
Author

JavaScript Fetch

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment