Skip to content

Instantly share code, notes, and snippets.

@shahriar-shojib
Last active November 11, 2020 19:24
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 shahriar-shojib/10adf21298d0571b1fb47b95a7359a68 to your computer and use it in GitHub Desktop.
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
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