nodejs使⽤fetch获取WebAPI
在上⼀篇《》中,已经获取到了accessToken,现时需要获取WebAPI的数据,选择了node-fetch来获取数据
node-fetch是使⽤promise的写法,对于习惯了promise写法的⼈来说,还是⾮常容易的
这⾥提醒⼀下,公司上⽹是通过代理的⽅式来上⽹的,那么在获取外⽹的地址时,如果没通过代理,则获取不到数据,在这⾥,我加⼊了代理node-https-proxy-agent,关于使⽤,可以看⽂章最后的参考地址
var fetch = require('node-fetch');
var defaultConfig = require('../config/default.json');
var HttpsProxyAgent = require('https-proxy-agent');
searchGarmentStyle: function (garmentStyleNo, access_token) {
var queryEntity = {
"filterType": "LEAF",
"filters": [{}],
"attributeName": "item_number",
"searchOperator": "eq",
"filterValue": garmentStyleNo
}
var garmentstyles = [];
// Set up the request
return new Promise(function (resolve, reject) {
try {
//-------------------------------------------------------------------------------------------------------------
fetch(GarmentStyleSigleApi,
{
agent: new HttpsProxyAgent('192.168.27.4:8083'),
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer ' + access_token
},
body: JSON.stringify(queryEntity)
})
.
then((response) => {
return response.json();
})
.then((responseJsonData) => {
var getresponse = responseJsonData;
if (sultType === "SUCCESS") {
if (sults) {
if (sults[0].data) {
var getdata = sults[0].data;
for (let i = 0; i < getdata.length; i++) {
garmentstyles.push(getdata[i]);
}
resolve(garmentstyles);
}
else {
reject(new Error('WebAPI Error :sults[0].data Value Is Null Or Empty'));
}
}
else {
reject(new Error('WebAPI Error :sults Value Is Null Or Empty'));
}
}
else {
reject(new Error('WebAPI Error :resultType Value Is ' + sultType));
}
})
.catch((error) => {
reject(new Error('WebAPI Error :' + ssage));
});
} catch (e) {
reject(e);
}
});
}
};
fetch最佳用法调⽤(这⾥与获取token的⽅法进⾏合并):
var garmentstyle_helper = require('./service/garment_style_search');
//get token
Token()
.then((token_object) => {
// console.log(token_object.accessToken);
//call webapi
garmentstyle_helper
.searchGarmentStyle(garmentStyleNo, token_object.accessToken)
.
then((GarmentStyles) => {
if (GarmentStyles && GarmentStyles.length > 0) {
//foreach data
for (var getstyle of GarmentStyles) {
// add message
var message = new builder.Message()
.text(getstyle.linePlanProducts.productID + '(' + getstyle.linePlanProducts.productVersion + getstyle.linePlanProducts.productVersionSerialNo + ')')      .attachmentLayout(builder.AttachmentLayout.carousel)
.attachments(getstyle.linePlanProducts.productMaterialConfigs.map(garmentStyleColorwayAttachment));
session.send(message);
}
}
else {
// no found
session.send('can not found garment style \"%s\"', garmentStyleNo);
}
},
(err) => {
session.send('[searchGarmentStyle Error:]' + ssage ? ssage : '');
});
}, (error) => {
session.send('[getToken Error:]' + ssage ? ssage : '');
});