在上一篇《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. 前端将markdown转换成html

    实现过程: 1. npm引入:npm install marked --save 2.在需要的文件(.ts)里import Marked from "marked";   如果.j ...

  2. css 给body设置背景图片

  3. 【题解】ZJOI2007报表统计

    洛谷传送门 主要思路大概也是差不多的,对于两种询问分别用线段树与平衡树来维护. 1.MIN_SORT_GAP:显然平衡树简单操作,来一发前驱.后继即可. 2.MIN_GAP:这一个我用的是线段树:可以 ...

  4. clientWidth、clientHeight、offsetWidth、offsetHeight以及scrollWidth、scrollHeight

    clientWidth.clientHeight.offsetWidth.offsetHeight以及scrollWidth.scrollHeight是几个困惑了好久的元素属性,趁着有时间整理一下 1 ...

  5. dns服务 很多问题,后续再研究

    慕课网:http://www.imooc.com/video/5220 参考:http://jingyan.baidu.com/article/870c6fc32c028eb03fe4be30.htm ...

  6. 如何在Javascript中利用封装这个特性

    对于熟悉C#和Java的兄弟们,面向对象的三大思想(封装,继承,多态)肯定是了解的,那么如何在Javascript中利用封装这个特性呢? 我们会把现实中的一些事物抽象成一个Class并且把事物的属性( ...

  7. Collection与Map的对比

    Map:HashMap.HashTable  如何在它们之间选择  一.Array , Arrays  Java所有“存储及随机访问一连串对象”的做法,array是最有效率的一种.  1.  效率高, ...

  8. PHP正则匹配与替换的简单例子

    PHP正则匹配与替换的简单例子,含一个匹配获取加租字体例子和一个匹配替换超链接的例子. 1.查找匹配 <b> 与 </b> 标签的内容: <?php $str = &qu ...

  9. 清理/var/spool/clientmqueue目录释放大量空间

    清理/var/spool/clientmqueue目录可以释放大量空间,具体命令是:ls | xargs rm -f 文件太大,rm -rf会由于参数太多而无法删除,所以需要用上面的命令. “Argu ...

  10. 【数据结构】bzoj1636/bzoj1699排队

    Description 每天,农夫 John 的N(1 <= N <= 50,000)头牛总是按同一序列排队. 有一天, John 决定让一些牛们玩一场飞盘比赛. 他准备找一群在对列中为置 ...