How to use the request function in request

To help you get started, we’ve selected a few request examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github simonknittel / discord-bot-api / src / index.js View on Github external
function checkForUpdates() {
    // Request the GitHub API
    request({
        url: 'https://api.github.com/repos/simonknittel/discord-bot-api/releases/latest',
        json: true,
        headers: {
            'User-Agent': 'simonknittel', // Needed otherwise the GitHub API will reject the request
        },
    }, (error, response, body) => {
        if (error || response.statusCode !== 200) {
            console.error('error:', error);
            console.error('response.statusCode:', response.statusCode);
            console.error('body:', body);
            console.log(''); // Empty line

            return false;
        }

        const currentVersion = packageJSON.version;
github fooey / node-gw2guilds / raw / get.fg.babel.js View on Github external
const localRoot = './fg';


let dlQueue = async.queue(function (task, cb) {
    console.log('download %s to %s', task.remotePath, task.localPath);
    downloadFile(task.remotePath, task.localPath, cb);
}, 8);


/*
*
*   MAIN
*
*/

request(
    'https://api.guildwars2.com/v2/emblem/foregrounds?ids=all',
    (err, response, body) => {
        const data = JSON.parse(body);

        _.each(data, (fg) => {
            _.each(fg.layers, (remotePath, layerIndex) => {
                const localPath = path.resolve(localRoot, `${fg.id}-${layerIndex}.png`);
                // console.log(localRoot, fg.id, layerIndex, localPath);
                dlQueue.push({
                    remotePath,
                    localPath,
                });
            });
        });
    }
);
github chriszarate / sheetrock / src / lib / transport.js View on Github external
function get(response, callback) {
  const transportOptions = {
    headers: {
      'X-DataSource-Auth': 'true',
    },
    timeout: 5000,
    url: response.request.url,
  };

  request(transportOptions, (error, resp, body) => {
    if (!error && resp.statusCode === 200) {
      try {
        const data = JSON.parse(body.replace(/^\)]\}'\n/, ''));
        response.loadData(data, callback);
        return;
      } catch (ignore) { /* empty */ }
    }

    const errorCode = resp && resp.statusCode ? resp.statusCode : null;
    const errorMessage = error && error.message ? error.message : 'Request failed.';

    callback(new SheetrockError(errorMessage, errorCode));
  });
}
github oaeproject / Hilary / packages / oae-preview-processor / lib / processors / link / flickr.js View on Github external
const _getFlickrPhoto = function(ctx, id, callback) {
  const config = _getConfig();

  const url = util.format(
    '%s?method=flickr.photos.getInfo&api_key=%s&photo_id=%s&format=json&nojsoncallback=1',
    apiUrl,
    config.apiKey,
    id
  );
  request(url, (err, response, body) => {
    if (err) {
      log().error({ err, body }, 'An unexpected error occurred getting a Flickr photo');
      return callback(err);
    }

    if (response.statusCode !== 200) {
      err = { code: response.statusCode, msg: body };
      log().error({ err }, 'An unexpected error occurred getting a Flickr photo');
      return callback(err);
    }

    // Try and parse the Flickr response, returning with an error if it is not valid JSON
    let info = null;
    try {
      info = JSON.parse(body);
    } catch (error) {
github openaq / openaq-api / test / test-countries.js View on Github external
it('should return properly', function (done) {
    request(apiUrl + 'countries', function (err, response, body) {
      expect(err).to.be.null;
      expect(response.statusCode).to.equal(200);

      var res = JSON.parse(body);
      expect(res.results.length).to.equal(5);
      done();
    });
  });
github superfeedr / superfeedr-pshb / src / lib / index.js View on Github external
_request (params, cb) {
    params.auth = this.auth
    if (!params.headers) {
      params.headers = {}
    }
    params.headers['Accept'] = 'application/json'
    params.headers['User-Agent'] = USER_AGENT

    request(params, (err, res, body) => {
      if (err) return cb(err)

      if (res.statusCode < 200 || res.statusCode >= 300) {
        console.error(body)
        return cb(new Error(`HTTP ${res.statusCode}`))
      }

      if (/^application\/json/.test(res.headers['content-type'])) {
        var json
        try {
          json = JSON.parse(body)
        } catch (e) {
          return cb(e)
        }
        cb(null, json)
      } else {
github anther / smashladder-desktop / app / actions / builds.js View on Github external
return new Promise((resolve, reject) => {
				progress(request(build.download_file), {})
					.on('progress', (state) => {
						dispatch({
							type: BUILD_DOWNLOAD_PROGRESS_UPDATE,
							payload: {
								build,
								percent: state.percent
							}
						});
						console.log('progress', state);
					})
					.on('error', (err) => {
						console.error(err);
						dispatch({
							type: DOWNLOAD_BUILD_ERROR,
							payload: {
								build,
github webdevstar / Dashborad / src / services / services.js View on Github external
getPopularTermsTimeSeries(siteKey, accountName, datetimeSelection, timespanType, selectedTerm, dataSource, callback) {
        let formatter = Actions.constants.TIMESPAN_TYPES[timespanType];
        let hostname = blobHostnamePattern.format(accountName);
        let blobContainer = TIMESERIES_BLOB_CONTAINER_NAME;

        let url = `${hostname}/${blobContainer}/${dataSource}/${momentToggleFormats(datetimeSelection, formatter.format, formatter.blobFormat)}/${selectedTerm}.json`;
        let GET = {
            url: url,
            json: true,
            withCredentials: false
        };

        request(GET, callback);
    },
github nylas-mail-lives / nylas-mail / internal_packages / github-contact-card / lib / github-user-store.es6 View on Github external
_githubRequest(url, callback) {
    return request({url: url, headers: {'User-Agent': 'request'}, json: true}, callback);
  }
}
github artsy / metaphysics / src / integration / index.js View on Github external
return new Promise((resolve, reject) =>
    request(url, options, (err, response) => {
      if (err) return reject(err)
      resolve(JSON.parse(response.body))
    })
  )