async manifestJSON() { const response = await fetch( `https://api.github.com/repos/${this.repo.owner}/${this.repo.name}/contents/manifest.json` ); return JSON.parse(Buffer.from((await response.json()).content, 'base64').toString()); }
function sendRequest (opts) { const options = { headers: { 'User-Agent': 'nodejs.org release blog post script' }, ...opts } return fetch(options.url, options).then(resp => { if (resp.status !== 200) { throw new Error(`Invalid status code (!= 200) while retrieving ${options.url}: ${resp.status}`) } return options.json ? resp.json() : resp.text() }) }
async downloadRepo() { const url = `https://github.com/${this.repo.owner}/${this.repo.name}/archive/master.tar.gz`; const writer = fs.createWriteStream(this.repoArchivePath); (await fetch(url)).body.pipe(writer); return new Promise((resolve, reject) => { writer.on('finish', resolve); writer.on('error', reject); }); }
function callAPI({ path, method, data }) { const ROOT_URI = `https://${process.env.MAILCHIMP_REGION}.api.mailchimp.com/3.0`; return fetch(`${ROOT_URI}${path}`, { method, headers: { Accept: 'application/json', Authorization: `Basic ${Buffer.from(`apikey:${process.env.MAILCHIMP_API_KEY}`).toString( 'base64', )}`, }, body: JSON.stringify(data), }); }
export default function fetchBrasilAPIService (cepWithLeftPad) { const url = `https://brasilapi.com.br/api/cep/v1/${cepWithLeftPad}` const options = { method: 'GET', mode: 'cors', headers: { 'content-type': 'application/json;charset=utf-8' } } return fetch(url, options) .then(parseResponse) .then(extractCepValuesFromResponse) .catch(throwApplicationError) }
const compose = (path: string, fetchOptions?: Object = {}) => { if (!COMPOSE_API_TOKEN) { throw new Error('Please specify the COMPOSE_API_TOKEN env var.'); } return fetch(`https://api.compose.io/${path}`, { ...fetchOptions, headers: { 'Content-Type': 'application/json', ...(fetchOptions.headers || {}), Authorization: `Bearer ${COMPOSE_API_TOKEN}`, }, }); }
describe('node-fetch', function() { setupPolly({ adapters: ['node-http'], persister: 'fs', persisterOptions: { fs: { recordingsDir: path.resolve(__dirname, '../recordings') } } }); it('should work', async function() { const res = await fetch('https://jsonplaceholder.typicode.com/posts/1'); const post = await res.json(); expect(res.status).to.equal(200); expect(post.id).to.equal(1); }); });
/** * @param {string} url The url that the post request targets. * @param {string} body The body of the post request. * @param {string} idToken Bearer token used to authorize the iap request. * @param {string} userAgent The user agent to identify the requester. */ const makeIapPostRequest = async (url, body, idToken, userAgent) => { const res = await fetch(url, { method: 'POST', headers: { 'User-Agent': userAgent, Authorization: `Bearer ${idToken}`, }, body: JSON.stringify(body), }); if (!res.ok) { const err = await res.text(); console.error('Error making IAP post request:', err.message); throw new Error(err); } }
const resolveLuUriContent = async function(srcId, toResolve, luObjects) { let uri = toResolve.filePath || undefined; if (uri !== undefined) { let response; try { response = await fetch(uri, { method: 'GET' }); } catch (err) { // throw, invalid URI let errorMsg = `URI: "${uri}" appears to be invalid. Please double check the URI or re-try this parse when you are connected to the internet.`; let error = BuildDiagnostic({ message: errorMsg, range: luImport.Range }) throw (new exception(retCode.errorCode.INVALID_URI, error.toString(), [error])); } var res = await response.buffer(); var encodedRes = helpers.fixBuffer(res); luObjects.push(new luObject(encodedRes, new luOptions(toResolve.filePath, toResolve.includeInCollate))); } }
const fetchStory = async (storyId) => { return (await fetch(`https://hacker-news.firebaseio.com/v0/item/${storyId}.json`)).json(); }
export default function fetchCorreiosService (cepWithLeftPad, proxyURL = '') { const url = `${proxyURL}https://apps.correios.com.br/SigepMasterJPA/AtendeClienteService/AtendeCliente` const options = { method: 'POST', body: `<?xml version="1.0"?>\n<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:cli="http://cliente.bean.master.sigep.bsb.correios.com.br/">\n <soapenv:Header />\n <soapenv:Body>\n <cli:consultaCEP>\n <cep>${cepWithLeftPad}</cep>\n </cli:consultaCEP>\n </soapenv:Body>\n</soapenv:Envelope>`, headers: { 'Content-Type': 'text/xml;charset=UTF-8', 'cache-control': 'no-cache' } } return fetch(url, options) .then(analyzeAndParseResponse) .catch(throwApplicationError) }
export default function fetchViaCepService (cepWithLeftPad, proxyURL = '') { const url = `${proxyURL}https://viacep.com.br/ws/${cepWithLeftPad}/json/` const options = { method: 'GET', mode: 'cors', headers: { 'content-type': 'application/json;charset=utf-8' } } return fetch(url, options) .then(analyzeAndParseResponse) .then(checkForViaCepError) .then(extractCepValuesFromResponse) .catch(throwApplicationError) }
function callAPI({ path, method, data }) { const ROOT_URI = `https://${process.env.MAILCHIMP_REGION}.api.mailchimp.com/3.0`; return fetch(`${ROOT_URI}${path}`, { method, headers: { Accept: 'application/json', Authorization: `Basic ${Buffer.from(`apikey:${process.env.MAILCHIMP_API_KEY}`).toString( 'base64', )}`, }, body: JSON.stringify(data), }); }
const fetchUser = async (userId) => { return (await fetch(`https://hacker-news.firebaseio.com/v0/user/${userId}.json`)).json(); }
export default function fetchWideNetService (cepWithLeftPad, proxyURL = '') { const url = `${proxyURL}https://cep.widenet.host/busca-cep/api/cep/${cepWithLeftPad}.json` const options = { method: 'GET', mode: 'cors', headers: { 'content-type': 'application/json;charset=utf-8' } } return fetch(url, options) .then(analyzeAndParseResponse) .then(checkForWideNetError) .then(extractCepValuesFromResponse) .catch(throwApplicationError) }