Created
December 31, 2017 01:40
-
-
Save ViktorQvarfordt/78d64357049e0bc13c2d2c612230d4af to your computer and use it in GitHub Desktop.
VanillaJS HTTP Requests
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
// VanillaJS convenience methods for making HTTP requests. | |
window.http = (() => { | |
const logger = (err, data) => { | |
console.log(err || data) | |
} | |
const handleResponse = (req, cb) => { | |
let data | |
try { | |
data = JSON.parse(req.response) | |
} catch (err) { | |
cb(req) | |
} | |
if (data.error || req.status !== 200) { | |
cb(data) | |
} else { | |
cb(null, data) | |
} | |
} | |
return { | |
get: (url, cb) => { | |
if (!cb) cb = logger | |
const req = new XMLHttpRequest() | |
req.open('GET', url) | |
req.onload = () => handleResponse(req, cb) | |
req.onerror = () => cb(req) | |
req.send() | |
}, | |
getRaw: (url, cb) => { | |
if (!cb) cb = logger | |
const req = new XMLHttpRequest() | |
req.open('GET', url) | |
req.onload = () => { | |
if (req.status !== 200) { | |
cb(req) | |
} else { | |
cb(null, req.response) | |
} | |
} | |
req.onerror = () => cb(req) | |
req.send() | |
}, | |
post: (url, data, cb) => { | |
if (!cb) cb = logger | |
const req = new XMLHttpRequest() | |
req.open('POST', url) | |
req.setRequestHeader('Content-type', 'application/json; charset=utf-8') | |
req.onload = () => handleResponse(req, cb) | |
req.onerror = () => cb(req) | |
req.send(JSON.stringify(data)) | |
}, | |
put: (url, data, cb) => { | |
if (!cb) cb = logger | |
const req = new XMLHttpRequest() | |
req.open('PUT', url) | |
req.setRequestHeader('Content-type', 'application/json; charset=utf-8') | |
req.onload = () => handleResponse(req, cb) | |
req.onerror = () => cb(req) | |
req.send(JSON.stringify(data)) | |
}, | |
delete: (url, cb) => { | |
if (!cb) cb = logger | |
const req = new XMLHttpRequest() | |
req.open('DELETE', url) | |
req.onload = () => handleResponse(req, cb) | |
req.onerror = () => cb(req) | |
req.send() | |
}, | |
// This is nice for navigating to a new page with POST data. | |
submitForm: (data, action, method, target) => { | |
const form = document.createElement('form') | |
form.action = action || '' | |
form.method = method || 'POST' | |
form.target = target || '_self' | |
form.style.display = 'none' | |
const dataEl = document.createElement('textarea') | |
dataEl.name = 'json' | |
dataEl.value = JSON.stringify(data) | |
form.appendChild(dataEl) | |
document.body.appendChild(form) | |
form.submit() | |
} | |
} | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment