Last active
November 11, 2020 19:24
-
-
Save shahriar-shojib/10adf21298d0571b1fb47b95a7359a68 to your computer and use it in GitHub Desktop.
Javascript network request helper functions that I almost use all the time
This file contains 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 fetch = require('node-fetch'); | |
function get(url, headers = {}) { | |
return fetch(url, { | |
method: 'GET', | |
headers, | |
}).then((r) => r.json()); | |
} | |
async function post(url, payload, headers = {}) { | |
return await fetch(url, { | |
headers: { | |
'content-type': 'application/json', | |
...headers, | |
}, | |
body: JSON.stringify(payload), | |
method: 'POST', | |
}).then((r) => r.json()); | |
} | |
function postForm(url, body, returnsJSON = true, customHeader = {}) { | |
return fetch(url, { | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/x-www-form-urlencoded', | |
...customHeader, | |
}, | |
body, | |
}).then((r) => (returnsJSON ? r.json() : r.text())); | |
} | |
module.exports = { get, post, postForm }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment