How to use xhr - 10 common examples

To help you get started, we’ve selected a few xhr 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 energy-data / market-opportunities / test / login.js View on Github external
test.before(t => {
  // note: not bothering to restore this after the test, because anyway
  // the "real" one doesn't exist in non-browser situation
  xhr.XMLHttpRequest = fakeXhr = sinon.useFakeXMLHttpRequest()
})
github unageanu / container-js / lib-test / thatcher-env-js-cb738b9 / platform-commonjs.js View on Github external
* @param {Object} responseHandler
 * @param {Object} data
 */
Envjs.connection = function(xhr, responseHandler, data) {
    throw new Error('Envjs.connection');
    // THIS WILL BE REPLACED WITH NATIVE XHR IMPL
};

// XHR is a confusing bit of code in envjs.  Need to simplify.
// if you are lucky your impl has a XHR already
var XMLHttpRequestCore = require('xhr').XMLHttpRequest;

XMLHttpRequest = function() {
    XMLHttpRequestCore.apply(this, arguments);
};
XMLHttpRequest.prototype = new XMLHttpRequestCore();
XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
    // resolve relative URLs (server-side version doesn't do this,
    //  require absolute urls)
    //print("******* " + url);
    if (document.location) {
       url = Envjs.uri(url, document.location.href);
    } else {
        // sometimes document.location is null
    // should we always use baseURI?
    url = Envjs.uri(url, document.baseURI);
    }
    
    //print("******* " + url);
    require('xhr').XMLHttpRequest.prototype.open.apply(this, arguments);
    this.setRequestHeader('User-Agent', window.navigator.userAgent);
    this.setRequestHeader('Accept', 'image/png,image/*;q=0.8,*/*;q=0.5');
github keystonejs / keystone-test-project / client / lib / api.js View on Github external
post (url, options = {}, callback) {
		if (!options.headers) options.headers = {};
		options.headers[Keystone.csrf_header_key] = Keystone.csrf_token_value;
		xhr.post(url, options, (err, res, body) => {
			// Handle Unauthorized responses by redirecting to the signin page
			if (res && res.statusCode === 401) {
				alert('Please sign in to run the API Tests');
				var from = window.location.pathname;
				window.location.href = '/keystone/signin?from=' + from;
			} else {
				callback(err, res, body);
			}
		});
	},
};
github w3reality / three-geo / src / index.js View on Github external
return;
                }

                let name = `${api}-${zoompos.join('-')}.blob`;
                this.dumpBufferAsBlob(buffer, name);
            });
        };
        const dumpBlobForDebug = 0;

        if (api.includes('mapbox-terrain-vector')) {
            if (isOnline) {
                if (dumpBlobForDebug) {
                    xhrDumpBlob(uri, api, zoompos);
                    // return;
                }
                xhr({uri: uri, responseType: 'arraybuffer'}, (error, response, buffer) => {
                    if (error || !this.isAjaxSuccessful(response.statusCode)) {
                        cb(null);
                        return;
                    }
                    // console.log('mapbox -> buffer:', buffer); // ArrayBuffer(39353) {}
                    cb(new VectorTile(new Pbf(buffer)));
                });
            } else {
                xhr({uri: uri, responseType: 'blob'}, (error, response, blob) => {
                    // console.log('error, response, blob:', error, response, blob);
                    if (error || !this.isAjaxSuccessful(response.statusCode)) {
                        cb(null);
                        return;
                    }
                    this.blobToBuffer(blob, (buffer) => {
                        // console.log('blob -> buffer:', buffer); // ArrayBuffer(39353) {}
github janpaul123 / paperprograms / client / editor / EditorMain.js View on Github external
const targetTimeMs = 250;
    const beginTimeMs = Date.now();

    const done = () => {
      const elapsedTimeMs = Date.now() - beginTimeMs;
      clearTimeout(this._pollDebugUrlTimeout);
      this._pollDebugUrlTimeout = setTimeout(
        this._pollDebugUrl,
        Math.max(0, targetTimeMs - elapsedTimeMs)
      );
    };

    const program = this._selectedProgram(this.state.selectedProgramNumber);
    if (program) {
      const { editorId } = this.props.editorConfig;
      xhr.post(program.claimUrl, { json: { editorId } }, (error, response) => {
        if (error) {
          console.error(error); // eslint-disable-line no-console
        } else if (response.statusCode === 400) {
          this.setState({
            selectedProgramNumber: '',
            code: '',
            debugInfo: {},
          });
        } else {
          this.setState({ debugInfo: response.body.debugInfo });
        }
        done();
      });
    } else {
      done();
    }
github janpaul123 / paperprograms / client / camera / CameraMain.js View on Github external
_createHelloWorld = () => {
    xhr.post(
      getApiUrl(this.state.spaceData.spaceName, '/programs'),
      { json: { code: helloWorld } },
      error => {
        if (error) {
          console.error(error); // eslint-disable-line no-console
        }
      }
    );
  };
github PlotterClub / penplotPlayground / lib / penplot.js View on Github external
function save () {
    // capture frame at a larger resolution
    setToOutputSize();
    draw();

    if (isBrowser()) {
      const base64 = canvas.toDataURL().slice('data:image/png;base64,'.length);

      // resize back to original resolution
      resize();
      draw();

      if (process.env.NODE_ENV !== 'production') {
        xhr.post('/save', {
          json: true,
          body: {
            data: base64
          }
        }, err => {
          if (err) throw err;
        });
      } else {
        console.warn('Not yet implemented: save canvas to PNG in client-side / production.');
      }
    }
  }
github janpaul123 / paperprograms / client / editor / EditorMain.js View on Github external
_print = () => {
    const { code } = this.state;
    xhr.post(
      getApiUrl(this.props.spaceName, '/programs'),
      { json: { code } },
      (error, response) => {
        if (error) {
          console.error(error); // eslint-disable-line no-console
        } else {
          const { body } = response;
          this.setState({
            code,
            selectedProgramNumber: body.number,
            spaceData: body.spaceData,
            debugInfo: {},
          });
        }
      }
    );
github janpaul123 / paperprograms / client / editor / EditorMain.js View on Github external
_save = () => {
    const { code, selectedProgramNumber } = this.state;
    xhr.put(
      getApiUrl(this.props.spaceName, `/programs/${selectedProgramNumber}`),
      {
        json: { code },
      },
      error => {
        if (error) console.error(error); // eslint-disable-line no-console
      }
    );
  };
github ajb413 / crowdsalable-eth-token / app / pubnub-functions / sms-handler.js View on Github external
let messages = [];

  // Create an object for each number that will be SMSed.
  // Object array will be the POST body to ClickSend.
  for (let number of crowdPhoneNumbers) {
    messages.push({
      source: 'pubnub-blocks',
      from: 'cstoken',
      body: body,
      to: number,
      custom_string: `TOK-${crowdsaleName}`
    });
  }

  // POST to ClickSend API
  return xhr.fetch(uri, {
    'method'  : 'POST',
    'headers' : {
      'Authorization' : authorization,
      'Content-Type': 'application/json'
    },
    'body': JSON.stringify({
      'messages': messages
    }),
    'timeout' : 5000
  })
  .then((res) => {
    return request.ok();
  })
  .catch((err) => {
    console.error(err);
    return request.abort();