Skip to content

Instantly share code, notes, and snippets.

@ViktorQvarfordt
Created December 31, 2017 01:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ViktorQvarfordt/78d64357049e0bc13c2d2c612230d4af to your computer and use it in GitHub Desktop.
Save ViktorQvarfordt/78d64357049e0bc13c2d2c612230d4af to your computer and use it in GitHub Desktop.
VanillaJS HTTP Requests
// 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