How to use superagent

Comprehensive superagent code examples:

How to use superagent.head:

61
62
63
64
65
66
67
68
69
}

function onSuccess(videoData) {
  var path = videoData.video;
  console.log(`Got metadata about ${path}`);
  // const response = await superagent.head(path);
  // var total = response.headers["content-length"];
  var total = videoData.contentLength;
  console.log(`Got file length ${total}`);

How to use superagent.proxy:

38
39
40
41
42
43
44
45
46
  usage();
});

function proxyIfNeeded(request) {
  if (proxy != null && proxy !== '') {
    return request.proxy(proxy);
  }
  return request;
}

How to use superagent.delete:

134
135
136
137
138
139
140
141
142
if (method === 'GET') {
  req = request.get(url).withCredentials().query(body);
} else if (method === 'POST') {
  req = request.post(url).send(body);
} else if (method === 'DELETE') {
  req = request.delete(url).send(body);
}

req.set({ encoding: 'utf8', 'cache-control': 'no-cache', 'Content-Type': 'application/json' });

How to use superagent.apply:

1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
// hack to access the sockets created by node-xmlhttprequest
// see: https://github.com/driverdan/node-XMLHttpRequest/issues/44
const request = require("http").request;
const sockets = [];
http.request = function (opts) {
  const req = request.apply(null, arguments);
  req.on("socket", (socket) => {
    sockets.push(socket);
  });
  return req;

How to use superagent.Request:

120
121
122
123
124
125
126
127
128
129
        return '';
};
},{}],2:[function(require,module,exports){
'use strict';
const request = require('superagent');
const Request = request.Request;
const util = require('./util');
const globals = {
        requesting: 0
};

How to use superagent.getXHR:

2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
 * @api public
 */


Request.prototype.end = function(fn){
  var self = this;
  var xhr = this.xhr = request.getXHR();
  var data = this._formData || this._data;


  if (this._endCalled) {
    console.warn("Warning: .end() was called twice. This is not supported in superagent");

How to use superagent.body:

2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
};


/**
 * Override default response body parser
 *
 * This function will be called to convert incoming data into request.body
 *
 * @param {Function}
 * @api public
 */

How to use superagent.responseType:

242
243
244
245
246
247
248
249
250
251
    var request = requestBuilder
        .set('Authorization', 'Bearer ' + accessToken)
        .set(this._headers)
        .set('SdkVersion', "graph-js-" + packageInfo.version);
    if (this._responseType !== undefined) {
        request.responseType(this._responseType);
    }
    return request;
};
GraphRequest.prototype.query = function (queryDictionaryOrString) {

How to use superagent.del:

80
81
82
83
84
85
86
87
88
89
 * @param {String} path the relative path
 * @param {Object} data an object containing extra values
 * @param {Function} callback the callback to invoke when the request completes
 */
var tinderDelete = function(path, data, callback) {
  request.del(TINDER_HOST + path)
    .set(getRequestHeaders())
    .send(data)
    .end(callback);
};

How to use superagent.function:

36
37
38
39
40
41
42
43
44
45
 * @param {function} superagent Superagent constructor function (i.e. require('superagent') )
 */
function set(superagent)
{
        old_xhr = superagent.getXHR ;
        superagent.getXHR = function()
        {
                return new gmxhr() ;
        } ;
}

How to use superagent.Response:

155
156
157
158
159
160
161
162
163
164
// Not necessary in Titanium SDK 3.4, HTTPClient#getResponseHeader is (as the
// standard states) case insensitive.
// See https://jira.appcelerator.org/browse/TIMOB-17585 for reference,
// and https://github.com/appcelerator/titanium_mobile/pull/6053

var originalSetHeaderProperties = request.Response.prototype.setHeaderProperties;
request.Response.prototype.setHeaderProperties = function (header) {
  this.header['content-type'] =
    this.xhr.getResponseHeader('content-type') ||
    this.xhr.getResponseHeader('Content-Type');

How to use superagent.put:

67
68
69
70
71
72
73
74
75
76
 * @param {String} path the relative path
 * @param {Object} data an object containing extra values
 * @param {Function} callback the callback to invoke when the request completes
 */
var tinderPut = function(path, data, callback) {
  request.put(TINDER_HOST + path)
    .set(getRequestHeaders())
    .send(data)
    .end(callback);
};

How to use superagent.url:

964
965
966
967
968
969
970
971
972
973
 * @param {String} type - the load balance type
 * @param {Function} fn - the load balance function, it shoud return an integer
 * @since 2.7.0
 * @example
 * client.addAlgorithm('getByUrl', (request) => {
 *   return request.url.length;
 * });
 */
addAlgorithm(type, fn) {
  return internal(this).influx.addAlgorithm(type, fn);

How to use superagent.agent:

104
105
106
107
108
109
110
111
112
113
/*
 * Used to save and return cookies in a node.js (non-browser) setting,
 * if this.enableCookies is set to true.
 */
if (typeof window === 'undefined') {
  this.agent = new superagent.agent();
}

// API Routes
this.activityFeed = new ActivityFeed(this);

How to use superagent.serializeObject:

82
83
84
85
86
87
88
89
90
91
  xhr.validatesSecureCertificate = this._validatesSecureCertificate
}

// querystring
if (query) {
  query = request.serializeObject(query);
  this.url += ~this.url.indexOf('?')
    ? '&' + query
    : '?' + query;
}

How to use superagent.types:

4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
/**
 * Set Content-Type to `type`, mapping values from `request.types`.
 *
 * Examples:
 *
 *      superagent.types.xml = 'application/xml';
 *
 *      request.post('/')
 *        .type('xml')
 *        .send(xmlstring)

How to use superagent.default:

1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
  "params": _params
};
// console.log('PKG', pkg)

/* Request Elasticsearch query. */
response = await _superagent.default.post(endpoint).set('accept', 'json').send(pkg).catch(_err => {
  // console.error(_err)

  if (_err && _err.response && _err.response.text) {
    error = JSON.parse(_err.response.text);

How to use superagent.post:

46
47
48
49
50
51
52
53
54
55
apiRoutes.get('/robotapi', (req, res) => {
  let response=res
  let info = req.query.message
  let userid = req.query.id
  let key = '069e90c4262243bf964ad95014371384'
  superagent.post('http://www.tuling123.com/openapi/api')
  .send({info, userid, key})
  .end((err,res) => {
    if(err){
      console.log(err)

How to use superagent.get:

142
143
144
145
146
147
148
149
150
151
  'beijing',
  'capetown',
]
function getWeatherOfRandomCity (request, response) {
  const city = CITIES[Math.floor(Math.random() * CITIES.length)]
  superagent.get(`wttr.in/${city}`)
    .end((err, res) => {
      if (err) {
        console.log('O snap')
        return response.status(500).send('There was an error getting the weather, try looking out the window')