How to use the superagent.post function in superagent

To help you get started, we’ve selected a few superagent 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 MyScienceWork / PolarisOS / app / modules / entities / exporter / controllers / sword.js View on Github external
}

    const { url, password, login } = hal_config;

    const publication = await EntitiesUtils.retrieve_and_get_source('publication', pid);
    if (!publication) {
        throw Errors.InvalidEntity;
    }

    const xml_tei = await HalExporter.transform_publication_to_hal(publication);
    const files = Utils.find_value_with_path(publication, 'files'.split('.')) || [];
    const my_file = files.find(f => f.is_master) || (files.length > 0 ? files[0] : null);
    const skip_files = files.length === 0 || ((my_file.access.restricted || my_file.access.confidential) && !my_file.access.delayed);
    // console.log(xml_tei);

    const req = Request.post(url)
        .set('Packaging', 'http://purl.org/net/sword-types/AOfr')
        .auth(encodeURIComponent(login), encodeURIComponent(password));

    const result_promise = new Promise((resolve, reject) => {
        req
        .on('response', result => resolve(result)).on('error', err => reject(err));
    });
    console.log(xml_tei);
    if (skip_files) {
        req.set('Content-Type', 'text/xml')
            .send(xml_tei)
            .end();
    } else {
        req
            .set('Content-Type', 'application/zip')
            .set('Content-Disposition', 'attachment; filename=meta.xml');
github groupwrite-io / groupwrite.io / src / components / GamePage.vue View on Github external
syncText: function () {
      // Sync to server
      console.log(`Syncing text for ${this.sharedState.playerId}`)
      request.post('/api/suggest', {
        playerId: this.sharedState.playerId,
        suggestion: this.sharedState.suggestionText
      }, function (err, state) {
        // handle error
        // https://github.com/groupwrite-io/groupwrite.io/issues/58
        if (err) {
          window.alert(err + '\r\n' + state.text)
        }
      })
    },
    theend: function () {
github alex1504 / node-guita-spider / spiders / src / spider_ccjita.js View on Github external
async _getSongInfo(name) {
        const proxyServer = proxyServers[Math.floor(proxyServers.length * Math.random())];
        return await superagent
            .post('http://music.163.com/api/search/pc')
            // .proxy(proxyServer)
            .set({'User-Agent': userAgent.getRandom()})
            .timeout(this.timeout)
            .type('form')
            .send({
                s: name,
                type: '1'
            }).then(res => {
                res = JSON.parse(res.text);
                const songs = res.result && res.result.songs;
                if (songs && songs.length) {
                    return {
                        song_poster: songs[0].album.picUrl,
                        author_name: songs[0].artists[0].name
                    }
github repetere / periodicjs / public / extensions / periodicjs.ext.admin / js / main_build.js View on Github external
ajaxforms[x].addEventListener("submit",function(e){
				var f = e.target;
				if(f.getAttribute("data-beforesubmitfunction")){
					var beforesubmitFunctionString = f.getAttribute("data-beforesubmitfunction"),
					beforefn = window[beforesubmitFunctionString];
					// is object a function?
					if (typeof beforefn === "function"){beforefn(e)};
				}
				var formData = new formobj(f);
				
				request
					.post(f.action)
					.set('x-csrf-token',document.querySelector('input[name=_csrf]').value)
					.set('Accept', 'application/json')
					.query({ format: 'json' })
					.send(formData)
					.end(function(error, res){
						if(res && res.body && res.body.result==='error'){
							ribbonNotification.showRibbon( res.body.data.error,4000,'error');
						}
						else if(res && res.clientError){
							ribbonNotification.showRibbon( res.status+": "+res.text,4000,'error');
						}
						else if(error){
							ribbonNotification.showRibbon( error.message ,4000,'error');
						}
						else{
github promethe42 / cocorico / webhook / index.js View on Github external
'Message failed for too long, skipping');
          ch.ack(msg);
          return;
        }
      }

      // Skip invalid messages
      if (!isWebhookEvent(msg.content)) {
        log.error({ message: msg }, 'Invalid message, skipping');
        ch.ack(msg);
        return;
      }

      // Send HTTP request to remote webhook
      log.info({ message: msg }, 'Calling webhook');
      request
        .post(msg.content.url)
        .send({event: msg.content.event})
        .end((err3, res) => {
          if (err3 || res.error) {
            if (err3) {
              log.error({ error: err3 },
                'Failed to call webhook, retrying later');
            } else if (res.error) {
              log.error({ http_status: res.status },
                'Failed to call webhook, retrying later');
            }
            if (!msg.content.firstTriedAt) {
              msg.content.firstTriedAt = Date.now();
            }
            msg.content.lastTriedAt = Date.now();
            // Requeue updated message
github paperjs / woods / lib / liveReload.js View on Github external
changed = function(url) {
		request.post(changedUrl)
		.send({ files: [ url ? url : 'index.html'] })
		.end(function(error, res) {
			if (error) {
				console.log(error);
				startServer();
			}
		});
	};
	changedFile = function(uri) {
github amituuush / gomocha / customer / components / App / App.js View on Github external
_handleOrderSubmit: function() {

        if (this.state.pickupTime === true) {
            var expectedPickupTime = moment().add(this.state.durationSeconds, 's').format('LT');
        } else {
            var expectedPickupTime = '';
        }

        var date = moment().format('l');
        var time = moment().format('LT');

        request.post('/api/orders')
            .set('Content-Type', 'application/json')
            .send({
                username: this.state.username,
                items: this.state.items,
                specialInstructions: this.state.specialInstructions,
                selectedShop: this.state.selectedShop.name,
                selectedShop_id: this.state.selectedShop.place_id,
                favorited: this.state.favorite,
                date: date,
                time: time,
                timeUntilArrival: this.state.duration,
                secondsUntilArrival: this.state.durationSeconds,
                timeSelectedForPickup: this.state.pickupTime,
                expectedPickupTime: expectedPickupTime,
                completed: false
            })
github lancetw / react-isomorphic-bundle / src / shared / actions / SignupActions.js View on Github external
return new Promise((resolve, reject) => {
    request
      .post('https://www.google.com/recaptcha/api/siteverify')
      .type('form')
      .send(form)
      .end(function (err, res) {
        if (!err && res.body) {
          resolve(res.body)
        } else {
          reject(err)
        }
      })
  })
}
github lijinke666 / nodeJs-demos / 图片上传到七牛 / upload.js View on Github external
if(!avatar || !validator.isBase64(base64Data)) return next(JSON.stringify(errs.not_avatar))
        const key = getUploadKey()
        const type = avatar.match(/^data:image\/(\w*)/)[1] || "png";        //拿到当前是什么图片 jpeg/png

        let imageData = Buffer.from(base64Data, 'base64');         //使用 Buffer转换成二进制

        const filename = `${tempAvatarDir}/${Date.now()}.${type}`
        fs.writeFileSync(filename,imageData,'binary')
        const avatarSize = sizeOf(filename)

        httpLogger.info("/avatar-tempAvatar-save-success:",avatarSize)
        //长宽限制200
        if (avatarSize.width === avatarSize.width && avatarSize.height === avatarSize.height) {
            httpLogger.info('/avatar-start-upload')
            request
                .post(uploadUrl)
                .field('key', key)
                .field('name', key)
                .field('token', TOKEN)
                .attach('file', imageData, key)
                .set('Accept', 'application/json')
                .end((err, data) => {
                    if (err) {
                        errorLogger.info('/avatar-upload-faild:', err)
                        return next(JSON.stringify(errs.avatar_upload_faild))
                    }
                    httpLogger.info('/avatar-end-upload:', data)
                    res.resRawData = {
                        msg:cdnHost + key
                    }
                    next()