nodejs实现百度舆情接口应用示例


Posted in NodeJs onFebruary 07, 2020

本文实例讲述了nodejs实现百度舆情接口。分享给大家供大家参考,具体如下:

const URL = require('url');
const http = require('http');
const https = require('https');
const qs = require('querystring');
let trends = exports;
trends.getInstance = function () {
  return new Trends;
}
function Trends() {
  this.expireTime = 1800;
  this.accessKey = 'xxxxxxxx';
  this.secretKey = 'xxxxxxxx';
  this.userKey = 'xxxxxxxx';
  this.userSecret = 'xxxxxxxx';
  this.host = 'trends.baidubce.com';
  this.timestamp = _.time();
  this.utcTimestamp = _.utcTime();
}
Trends.prototype.request = async function (method, uri, params) {
  method = method.toUpperCase();
  let token = this.getToken();
  let headers = this.getHeaders(method, uri);
  params = Object.assign({}, params || {}, {
    'user_key': this.userKey,
    'token': token,
    'timestamp': this.timestamp
  });
  let url = `http://${this.host}${uri}`;
  return await this.httpRequest(method, url, params, headers);
}
Trends.prototype.getHeaders = function (method, uri) {
  let authorization = this.getAuthorization(method, uri);
  return {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Host': this.host,
    'x-bce-date': this.utcTimestamp,
    'Authorization': authorization,
  };
}
Trends.prototype.getAuthorization = function (method, uri) {
  let authString = `bce-auth-v1/${this.accessKey}/${this.utcTimestamp}/${this.expireTime}`;
  let signinKey = _.hmac(authString, this.secretKey, 'sha256');
  let header = {
    'host': this.host,
    'x-bce-date': _.urlencode(this.utcTimestamp)
  };
  let headerArr = [];
  for (let name in header) {
    let val = header[name];
    headerArr.push(`${name}:${val}`);
  }
  let headerKeyStr = Object.keys(header).sort().join(';');
  let requestStr = `${method}\n${uri}\n\n${headerArr.join('\n')}`;
  let signautre = _.hmac(requestStr, signinKey, 'sha256');
  return `${authString}/${headerKeyStr}/${signautre}`;
}
Trends.prototype.getToken = function () {
  return _.hmac(this.userKey + this.timestamp, this.userSecret);
}
Trends.prototype.httpRequest = async function (method, url, params, headers) {
  let urlObj = URL.parse(url);
  let protocol = urlObj.protocol;
  let options = {
    hostname: urlObj.hostname,
    port: urlObj.port,
    path: urlObj.path,
    method: method,
    headers: headers,
    timeout: 10000,
  };
  let postData = qs.stringify(params || {});
  return new Promise((resolve, reject) => {
    let req = (protocol == 'http:' ? http : https).request(options, (res) => {
      let chunks = [];
      res.on('data', (data) => {
        chunks.push(data);
      });
      res.on('end', () => {
        let buffer = Buffer.concat(chunks);
        let encoding = res.headers['content-encoding'];
        if (encoding == 'gzip') {
          zlib.unzip(buffer, function (err, decoded) {
            resolve(decoded.toString());
          });
        } else if (encoding == 'deflate') {
          zlib.inflate(buffer, function (err, decoded) {
            resolve(decoded.toString());
          });
        } else {
          resolve(buffer.toString());
        }
      });
    });
    req.on('error', (e) => {
      _.error('request error', method, url, params, e);
      resolve('');
    });
    req.on("timeout", (e) => {
      _.error('request timeout', method, url, params, e);
      resolve('');
    })
    if (method.toUpperCase() == 'POST') {
      req.write(postData);
    }
    req.end();
  });
}
module.exports = function () {
  return new Script;
}
function Script() {}
Script.prototype.run = async function () {
  let rst = this.getTaskList();
  console.log(rst);
}
Script.prototype.getTaskList = async function () {
  let params = {};
  let method = 'post';
  let uri = '/openapi/getTasklist';
  let rst = await _.trends.getInstance().request(method, uri, params);
  return rst;
}

希望本文所述对大家node.js程序设计有所帮助。

NodeJs 相关文章推荐
跟我学Nodejs(三)--- Node.js模块
May 25 NodeJs
浅谈NodeJS中require路径问题
May 07 NodeJs
Nodejs Express4.x开发框架随手笔记
Nov 23 NodeJs
Nodejs学习item【入门手上】
May 05 NodeJs
nodejs redis 发布订阅机制封装实现方法及实例代码
Dec 15 NodeJs
详解nodejs微信公众号开发——6.自定义菜单
Apr 13 NodeJs
ajax +NodeJS 实现图片上传实例
Jun 06 NodeJs
docker中编译nodejs并使用nginx启动
Jun 23 NodeJs
nodejs模块学习之connect解析
Jul 05 NodeJs
详解Nodejs 通过 fs.createWriteStream 保存文件
Oct 10 NodeJs
nodejs实现连接mongodb数据库的方法示例
Mar 15 NodeJs
Nodejs 数组的队列以及forEach的应用详解
Feb 25 NodeJs
使用nodeJS中的fs模块对文件及目录进行读写,删除,追加,等操作详解
Feb 06 #NodeJs
nodejs nedb 封装库与使用方法示例
Feb 06 #NodeJs
nodejs实现的http、https 请求封装操作示例
Feb 06 #NodeJs
Nodejs + Websocket 指定发送及群聊的实现
Jan 09 #NodeJs
nodeJs的安装与npm全局环境变量的配置详解
Jan 06 #NodeJs
Nodejs封装类似express框架的路由实例详解
Jan 05 #NodeJs
nodejs对mongodb数据库的增加修删该查实例代码
Jan 05 #NodeJs
You might like
php Mysql日期和时间函数集合
2007/11/16 PHP
thinkphp3查询mssql数据库乱码解决方法分享
2014/02/11 PHP
php中替换字符串中的空格为逗号','的方法
2014/06/09 PHP
thinkphp微信开之安全模式消息加密解密不成功的解决办法
2015/12/02 PHP
PHP获取对象属性的三种方法实例分析
2019/01/03 PHP
phpstorm 配置xdebug的示例代码
2019/03/31 PHP
推荐:极酷右键菜单
2006/11/29 Javascript
js自动生成对象的属性示例代码
2013/10/28 Javascript
js螺旋动画效果的具体实例
2013/11/15 Javascript
js中一个函数获取另一个函数返回值问题探讨
2013/11/21 Javascript
jquery常用方法及使用示例汇总
2014/11/08 Javascript
jQuery简单实现QQ空间点赞已经取消点赞
2015/04/02 Javascript
Js实现无刷新删除内容
2015/04/29 Javascript
全面解析Bootstrap中Carousel轮播的使用方法
2016/06/13 Javascript
什么是JavaScript中的结果值?
2016/10/08 Javascript
vue的token刷新处理的方法
2018/07/17 Javascript
Vue封装的可编辑表格插件方法
2018/08/28 Javascript
微信小程序 拍照或从相册选取图片上传代码实例
2019/08/28 Javascript
[06:53]2018DOTA2国际邀请赛寻真——为复仇而来的Newbee
2018/08/15 DOTA
分享一下Python 开发者节省时间的10个方法
2015/10/02 Python
python魔法方法-属性访问控制详解
2016/07/25 Python
Python数据操作方法封装类实例
2017/06/23 Python
opencv改变imshow窗口大小,窗口位置的方法
2018/04/02 Python
python打印9宫格、25宫格等奇数格 满足横竖斜相加和相等
2019/07/19 Python
Django xadmin开启搜索功能的实现
2019/11/15 Python
Keras中的两种模型:Sequential和Model用法
2020/06/27 Python
18-35岁旅游团的全球领导者:Contiki
2017/02/08 全球购物
COACH德国官方网站:纽约现代奢侈品牌,1941年
2018/06/09 全球购物
历史专业学生的自我评价
2014/02/28 职场文书
高中教师考核方案
2014/05/18 职场文书
中国梦演讲稿5分钟
2014/08/19 职场文书
中职三好学生事迹材料
2014/08/24 职场文书
公司证明怎么写
2014/09/22 职场文书
教师培训学习心得体会
2016/01/21 职场文书
80后创业总结的9条职场用人思想,记得收藏
2019/08/13 职场文书
导游词之青城山景区
2019/09/27 职场文书