easyhttp2.js
/**
* EasyHTTP Library
* Library for making HTTP requests
*
* @version 2.0.0
* @author Gabor Flamich
* @license MIT
*
**/
class EasyHTTP{
// Make an HTTP GET Request
get(url){
return new Promise((resolve, reject) => {
fetch(url)
.then(res => res.json())
.then(data => resolve(data))
.catch(err => reject(err));
});
}
// Make an HTTP POST Request
post(url, data){
return new Promise((resolve, reject) => {
fetch(url, {
method: 'POST',
headers:{
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(data => resolve(data))
.catch(err => reject(err));
});
}
// Make an HTTP PUT Request
put(url, data){
return new Promise((resolve, reject) => {
fetch(url, {
method: 'PUT',
headers:{
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(data => resolve(data))
.catch(err => reject(err));
});
}
// Make an HTTP PUT Request
delete(url){
return new Promise((resolve, reject) => {
fetch(url, {
method: 'PUT',
headers:{
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(() => resolve('Resource Deleted...'))
.catch(err => reject(err));
});
}
}
app.js
const http = new EasyHTTP;
// Get Users
const users = http.get('https://jsonplaceholder.typicode.com/users')
.then(data => console.log(data))
.catch(err => console.error(err))
// User data
const data = {
name: 'John Doe',
username: 'johndoe',
email: 'jdoe@gmail.com'
}
// Create Post
http.post('https://jsonplaceholder.typicode.com/users', data)
.then(data => console.log(data))
.catch(err => console.error(err))
// Update Post
http.put('https://jsonplaceholder.typicode.com/users/2', data)
.then(data => console.log(data))
.catch(err => console.error(err))
// Delete User
http.delete('https://jsonplaceholder.typicode.com/users/2', data)
.then(data => console.log(data))
.catch(err => console.error(err))
Leave a Reply