How to use request

Comprehensive request code examples:

How to use request.session:

221
222
223
224
225
226
227
228
229
230
231
232


app.get('/feedback', async function(request, response) {
  
  const Compra = require("./models/compra");
  const Cart = require("./models/Cart");
  const IdUsuario = request.session.passport.user.id;


    await Compra.updateOne({Id_transaccion:request.query.preference_id}, {$set:{Id_pago:request.query.payment_id,Orden_mercancia:request.query.merchant_order_id,Nombre_comprador:request.user.username,status:request.query.status}})
    await Cart.deleteMany({UsuarioId:IdUsuario});
    response.redirect('/');

How to use request.deleteAsync:

14
15
16
17
18
19
20
21
22
23
        headers: { "Ocp-Apim-Subscription-Key": this.apiKey }
    })
}

Vindexer.prototype.deleteBreakdown = function(id, params) {
    return _Request.deleteAsync({
        url: `${apiurl}/Breakdowns/${id}`,
        qs: params,
        headers: { "Ocp-Apim-Subscription-Key": this.apiKey }
    })

How to use request.category:

1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
})

socket.on('gini-request-ai-engine-processing', (request) => {
    if(request.category === "delete_intent" || request.category === "delete_entity"){
        let updated_AI_data = AI_ENGINE_PROCESSING_SERVICE.aiEngineProcessing(request);
        let type = request.category.split("_")[1];
        socket.emit("gini-response-ai-data", {data : updated_AI_data, type: type})
    }else{
      AI_ENGINE_PROCESSING_SERVICE.aiEngineProcessing(request);
    }

How to use request.save:

171
172
173
174
175
176
177
178
179
180
    })
};
const sentActionMsg = await messageId(moderatorsChanel, "№" + request.requestId + '\n#pending | #viber', false, optionsMod);
request.moderatorMsgID = sentMsg.message_id;
request.moderatorActionMsgID = sentActionMsg.message_id;
request.save();
//Inform user
bot.sendMessage(response.userProfile, [
    new TextMessage('Поки що ми не знайшли достатньої кількості доказів щодо цієї інформації. Ми нічого не знайшли або не бачили такої інформації у нашій базі перевірених новин.\n\nФактчекери почали опрацьовувати цей запит, це може зайняти до доби.')
]);

How to use request.DEFAULT_TIMEOUT:

7496
7497
7498
7499
7500
7501
7502
7503
7504

options.callback = callback
options.method = options.method || 'GET';
options.headers = options.headers || {};
options.body    = options.body || null
options.timeout = options.timeout || request.DEFAULT_TIMEOUT

if(options.headers.host)
  throw new Error("Options.headers.host is not supported");

How to use request.apply:

7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
      opts = JSON.parse(JSON.stringify(opts));
      opts.method = method;
    }


    var args = [opts].concat(Array.prototype.slice.apply(arguments, [1]));
    return request.apply(this, args);
  }
})


//

How to use request.messages:

351
352
353
354
355
356
357
358
359
360
361
  Request.putOrPost(
    "/character",
    character.id,
    { character: character },
    () => {
      Request.messages("Saved " + character.name);
    });
};


//========================================================================

How to use request.params:

4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
  }
};


// Returns the informations about the WAN for firmware devices
deviceListController.getWanInfo = async function(request, response) {
  let deviceId = request.params.id.toUpperCase();


  DeviceModel.findById(deviceId, function(error, matchedDevice) {
    // If an error occurred while finding the device
    if (error) {

How to use request.setHeader:

258
259
260
261
262
263
264
265
266
267
    this._error(err);
    return;
  }

  // add content length
  request.setHeader('Content-Length', length);

  ...
}.bind(this));
```

How to use request.errors:

342
343
344
345
346
347
348
349
350
351
352
353
};


//========================================================================
const saveCharacter = () => {
  if (!character.name) {
    Request.errors("Name is required");
    return;
  }


  Request.putOrPost(

How to use request.length:

968
969
970
971
972
973
974
975
976
977
    keys[i] +
        " elected to narrow from " +
        lastSearchedSongs[message.channel.id]
            .length +
        " to " +
        request.length
);
log.debug(
    "Previous values:\n\n" +
        JSON.stringify(

How to use request.cookie:

13
14
15
16
17
18
19
20
21
22
if (client.cookies) {
	var cookieUrl = urlObj.protocol + '//' + urlObj.host;
	var j = request.jar();
	for (var key in client.cookies) {
		if (client.cookies.hasOwnProperty(key)) {
			var cookie = request.cookie(key + '=' + client.cookies[key]);
			j.setCookie(cookie, cookieUrl);
		}
	}
	options.jar = j;

How to use request.putAsync:

74
75
76
77
78
79
80
81
82
83
        url: vttUrl
    });
}

Vindexer.prototype.reindexBreakdown = function(id, params) {
    return _Request.putAsync({
        url: `${apiurl}/Breakdowns/reindex/${id}`,
        qs: params,
        headers: { "Ocp-Apim-Subscription-Key": this.apiKey }
    })

How to use request.putOrPost:

105
106
107
108
109
110
111
112
113
114
115
        data[widget.name] = widget.value;
      }
    }
  });


  Request.putOrPost("/scenarios",
                    scenario.id,
                    { scenario: data },
                    resp => m.route.set("/scenarios/" + resp.data.id));
};

How to use request.debug:

78
79
80
81
82
83
84
85
86
    request.defaults(options);
}

export function debug(value?: boolean): boolean {
    if (value === undefined)
        return request.debug;
    else
        request.debug = value;
}

How to use request.status:

4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
  });
}

// If could not find the device
if (!matchedDevice) {
  return request.status(404).json({
    success: false,
    message: t('cpeNotFound', {errorline: __line}),
  });
}

How to use request.delete:

274
275
276
277
278
279
280
281
282
283

let requestObject = utilsForImport.requestForImport;
requestObject.url = utilsForImport.requestForImport.baseurl + url + 'keys/' + consumerKey;
requestObject.method = "DELETE";

request.delete(requestObject, function (err, res, body) {

    if(err){
        return console.log('Error in deleting auto-generated keys for the "' + appName + '"');
    }

How to use request.getSC:

280
281
282
283
284
285
286
287
288
289
290
291
292
            name: beijing_administrative_region_map[index].name
        })


    }


    // let result = await request.getSC(api, {})


    console.log("city_region_result:" + JSON.stringify(city_subways_result))
    // return result
}

How to use request.log:

7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
  timed_out = true
  var er = new Error('ETIMEDOUT')
  er.code = 'ETIMEDOUT'
  er.duration = options.timeout

  request.log.error('Timeout', { 'id':xhr._id, 'milliseconds':options.timeout })
  return options.callback(er, xhr)
}

// Some states can be skipped over, so remember what is still incomplete.

How to use request.postAsync:

100
101
102
103
104
105
106
107
108
109
    },
    //proxy: 'http://127.0.0.1:8888',
    strictSSL: false,
    jar: getTokenJar
};
return request.postAsync(loginOption).then((res)=> {
    let token = {cookies: getTokenJar.getCookieString(baiduUri)};
    this.setToken(token);
    return;
});

How to use request.del:

205
206
207
208
209
210
211
212
213
214
215
216
};




ClientBase.prototype._deleteHttp = function(path, callback, headers) {
  var url = this.baseApiUri + this._setAccessToken(path);
  request.del(url, this._generateReqOptions(url, path, null, 'DELETE', headers),
  function onDel(err, response, body) {
    if (!handleHttpError(err, response, callback)) {
      callback(null, body);
    }

How to use request.query:

107
108
109
110
111
112
113
114
115
116
 * 取出一级分类下面的所有网站,并且处理返回
 */
async info() {
  const { request, model } = this.ctx
  try {
    const { id, categoryId } = request.query
    let resData: any = []
    // 取所有子分类
    const categorys = await model.Category.find({ categoryId })
    const categoryIds = categorys.reduce((t, v) => [...t, v._id], [])

How to use request.getAsync:

42
43
44
45
46
47
48
49
50
51
    },
    //proxy: 'http://127.0.0.1:8888',
    jar: getTokenJar,
    strictSSL: false
};
return request.getAsync(getTokenOption).then((res)=> {
    let token = null;

    function callbackFromBaidu(result) {
        token = result.data.token;

How to use request.__getAuthedRequests:

811
812
813
814
815
816
817
818
819
820
821
822
});


// sync test because we need to get all the requests to confirm their validity
test('install a scoped module from authed private registry', (): Promise<void> => {
  return runInstall({}, 'install-from-authed-private-registry', async config => {
    const authedRequests = request.__getAuthedRequests();


    expect(authedRequests[0].url).toEqual('https://registry.yarnpkg.com/@types%2flodash');
    expect(authedRequests[0].headers.authorization).toEqual('Bearer abc123');
    expect(authedRequests[1].url).toEqual('https://registry.yarnpkg.com/@types/lodash/-/lodash-4.14.37.tgz');

How to use request.__setRequestResponses:

20
21
22
23
24
25
26
27
28
29
        expect(restClient[method]('')).toBeInstanceOf(Promise)
    })
})

it('json responses are pased to objects', () => {
    request.__setRequestResponses(null, {
        statusCode: 200
    }, JSON.stringify({ foo: 'bar' }))
    
    methods.forEach(method => {

How to use request.defaults:

51
52
53
54
55
56
57
58
59
60
61
      /<%apiKey%>/g,
      this.c.apiKey
    );
  }
  if ('request' in this.c) {
    request = requestRoot.defaults(this.c.request);
  }


  return this.c;
};

How to use request.body:

2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
connection.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
});


	var AM_Email = request.body.AM_Email;
	var AM_Password = request.body.AM_Password;
	if (AM_Email && AM_Password)
	 {
		connection.query('SELECT * FROM admin_master WHERE AM_Email = ? AND AM_Password = ?', [AM_Email, AM_Password], function(error, results, fields) {

How to use request.end:

637
638
639
640
641
642
643
644
645
646
        });
        request.on('error', error => {
          console.log(error);
        });
        request.write(JSON.stringify(itemData));
        request.end();

      }).catch();
    });
}

How to use request.write:

636
637
638
639
640
641
642
643
644
645
      });
    });
    request.on('error', error => {
      console.log(error);
    });
    request.write(JSON.stringify(itemData));
    request.end();

  }).catch();
});