Request API

Request used in send request to other domain.
https://blog.csdn.net/wuqingdeqing/article/details/99061026
https://blog.csdn.net/miss1128726/article/details/49976855
a basic sample of request:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var options = {
uri: 'http://api.example.fr/example/1.xml',
auth: {
user: 'test',
pass: 'test',
sendImmediately: false
}
};
request(options, function(error, response, body){
if (!error && response.statusCode == 200){
console.log('body : ' + body)
}
else{
console.log('Code : ' + response.statusCode)
console.log('error : ' + error)
console.log('body : ' + body)
}
});

This method has limitation for case that expecting to send datas to more than one server. Like, I want to send xml sais to multiple bdc servers, it turns out to only transfer datas to the last bdc. (using request(options, responseHandler)

---

A better way to resolve this problem is utilizing request-promise.
see official API description.
Here is my implementation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const rp = require('request-promise');
module.exports = class sample {
static async sampleFunc(para1, para2, para3) {
var opts = {
url: url,
method: 'GET',
auth:{
user: username,
pass: password,
sendImmediately: false
}
};
if(url.toLowerCase().startsWith('https')){
opts.ca = cert;
opts = Object.assign(Config.defaultOptions,opts); // sample
}
const responseHandler = (err, res, data) => {
// sample
}
await rp(opts).then(responseHandler).catch((err) => {
// print error in log
});
}
}

0717 UPDATE

ERROR implement request-promise above, note that it returns different paras from original request
Point:

  • resolveWithFullResponse: true,
  • then(reponse)
    Corrected:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    static async sampleFunc(para1, para2, para3) {
    var opts = {
    url: url,
    method: 'GET',
    resolveWithFullResponse: true,
    auth:{
    user: username,
    pass: password,
    sendImmediately: false
    }
    };
    ...
    const responseHandler = (res) => {
    // the res is a full response containing res.statusCode & res.body
    // sample
    }
    await rp(opts).then(responseHandler).catch((err) => {
    // print error in log
    });
    }