在上一篇《Nodejs获取Azure Active Directory AccessToken》中,已经获取到了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'); module.exports = {
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(defaultConfig.apiUrl.getGarmentStyleSigleApi,
{
agent: new HttpsProxyAgent('http://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 (getresponse.resultType === "SUCCESS") {
if (getresponse.results) {
if (getresponse.results[0].data) {
var getdata = getresponse.results[0].data; for (let i = 0; i < getdata.length; i++) {
garmentstyles.push(getdata[i]);
}
resolve(garmentstyles);
}
else {
reject(new Error('WebAPI Error :resultType.results[0].data Value Is Null Or Empty'));
}
}
else {
reject(new Error('WebAPI Error :resultType.results Value Is Null Or Empty'));
}
}
else {
reject(new Error('WebAPI Error :resultType Value Is ' + getresponse.resultType));
}
})
.catch((error) => {
reject(new Error('WebAPI Error :' + error.message));
}); } catch (e) {
reject(e);
} });
}
};

调用(这里与获取token的方法进行合并):

var garmentstyle_helper = require('./service/garment_style_search');

//get token
adal_manage.getToken()
.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);
} session.endDialog();
}
else {
// no found
session.send('can not found garment style \"%s\"', garmentStyleNo);
session.endDialog();
}
},
(err) => {
session.send('[searchGarmentStyle Error:]' + err.message ? err.message : '');
session.endDialog();
});
}, (error) => {
session.send('[getToken Error:]' + err.message ? err.message : '');
session.endDialog();
});

参考:https://github.com/bitinn/node-fetch

https://github.com/TooTallNate/node-https-proxy-agent

nodejs使用fetch获取WebAPI的更多相关文章

  1. nodejs 通过 get获取数据修改redis数据

    如下代码是没有报错的正确代码 我通过https获取到数据 想用redis set一个键值存储 现在我掉入了回调陷阱res.on 里面接收到的数据是data 里面如果放入 client.on('conn ...

  2. fetch获取json的正确姿势

    fetch要求参数传递,遇到请求无法正常获取数据,网上其他很多版本类似这样: fetch(url ,{ method: 'POST', headers:{ 'Accept': 'application ...

  3. react native android 上传文件,Nodejs服务端获取上传的文件

    React Native端 使用react-native-image-picker 做出选择图片的操作,选择完成后,直接将图片Post至服务器,保存在服务器的某个地方(保存图片的路径需要公开显示),并 ...

  4. nodejs异常处理过程/获取nodejs异常类型/写一个eggjs异常处理中间件

    前言 今天想写一下eggjs的自定义异常处理中间件,在写的时候遇到了问题,这个错误我捕获不到类型?? 处理过程,不喜欢看过程的朋友请直接看解决方法和总结 看一下是什么: 抛出的异常是检验失败异常Val ...

  5. nodejs微信开发获取token,ticket-1

    /* jshint -W079 */ /* jshint -W020 */ "use strict"; var _ = require("lodash"); v ...

  6. nodejs从服务器获取数据

    // 从服务器获取数据 request('http://192.168.1.7:8080/getDemo', function(error, response, body) { console.log ...

  7. nodejs 不同请求获取前端传的参数

    get方法 参数在req.query中获取 router.get('/', function(req, res, next) { console.log("reqquery:",r ...

  8. 怎么获取WebAPI项目中图片在服务端的路径

    1.这是我的项目结构. 2.路径格式为:[http://服务器域名/文件夹/文件.扩展名] 测试:假如我要获取到[logo_icon.jpg]这张图.在浏览器的地址栏中输入上面那个格式的路径. 3.可 ...

  9. nodejs gulp如何获取参数

    比如执行gulp test 如果需要获取test,使用命令process.argv即可 如果执行gulp test --module aaaa,这句话表示的意思执行gulp test,顺带参数modu ...

随机推荐

  1. 文件系统中 atime,lazytime,relatime 详聊

    atime,ctime,mtime是文件inode的三个时间戳,分别表示文件最近一次的访问时间:inode本身的更改(changed)时间:文件数据的更改(modify)时间:这几个概念还是很好区分. ...

  2. RadioGroup和GroupBox有什么区别?

    我在RadioGroup中放RadioButton和GroupBox中一样,搞不明白. radiogroup有个item属性都是radio控件,不需要拖控件上去.groupbox需要自己拖控件 分组的 ...

  3. iOS进阶--提高XCode编译速度、Xcode卡顿解决方案

    提升编译链接的速度主要有以下三个方式: 1. 提高XCode编译时使用的线程数 defaults write com.apple.Xcode PBXNumberOfParallelBuildSubta ...

  4. hihocoder 1457(后缀自动机+拓扑排序)

    题意 给定若干组由数字构成的字符串,求所有不重复子串的和(把他们看成十进制),答案mod(1e9+7) 题解: 类似后缀数组的做法,把字符串之间用':'连接,这里用':'是因为':'的ascii码恰好 ...

  5. SetLocalTime设置本地时间

    /***************************************************************** 函数名:EnableSetTimePriviledge 功 能:开 ...

  6. 安卓中使用iconfont

    https://www.cnblogs.com/dongweiq/p/5730212.html

  7. ibeacon UUID

    import sys; import uuid; s=uuid.uuid4().hex #s="f6bc15e0939046679be1866ec8a199dc" sys.stdo ...

  8. ntpq –p命令

    ntpq用来监视ntpd操作,ntpq -p查询网络中的NTP服务器,同时显示客户端和每个服务器的关系 [root@ ~]# ntpq -p remote refid st t when poll r ...

  9. Kafka自我学习-报错篇

    1. kafka启动出现:Unsupported major.minor version 52.0 错误,  具体的错误输出: Exception in thread "main" ...

  10. js获取当前url地址参数中文乱码问题

    网上看了一些关于此问题的文章,都说的不清不楚,有些更是乱七八糟,完全没法看,故此找了一篇能用的,借鉴作为笔记. //首先获取到当前页面的地址栏信息 var url = window.location. ...