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打包工具整合到鼠标右键的方法
May 11 NodeJs
利用NodeJS和PhantomJS抓取网站页面信息以及网站截图
Nov 18 NodeJs
nodeJS代码实现计算交社保是否合适
Mar 09 NodeJs
浅析nodejs实现Websocket的数据接收与发送
Nov 19 NodeJs
nodejs实现bigpipe异步加载页面方案
Jan 26 NodeJs
nodeJs内存泄漏问题详解
Sep 05 NodeJs
简单实现nodejs上传功能
Jan 14 NodeJs
用nodeJS搭建本地文件服务器的几种方法小结
Mar 16 NodeJs
初识NodeJS服务端开发入门(Express+MySQL)
Apr 07 NodeJs
Nodejs实现多房间简易聊天室功能
Jun 20 NodeJs
Nodejs实现多文件夹文件同步
Oct 17 NodeJs
分享五个Node.js开发的优秀实践 
Apr 07 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小偷相关截取函数备忘
2010/11/28 PHP
百度实时推送api接口应用示例
2014/10/21 PHP
PHP正则匹配日期和时间(时间戳转换)的实例代码
2016/12/14 PHP
php自定义函数br2nl实现将html中br换行符转换为文本输入中换行符的方法【与函数nl2br功能相反】
2017/02/17 PHP
PHP实现文件上传与下载
2020/08/28 PHP
javascript的push使用指南
2014/12/05 Javascript
javascript实时显示当天日期的方法
2015/05/20 Javascript
JavaScript的类型、值和变量小结
2015/07/09 Javascript
jqGrid 学习笔记整理——进阶篇(一 )
2016/04/17 Javascript
关于AngularJs数据的本地存储详解
2017/01/20 Javascript
微信小程序 循环及嵌套循环的使用总结
2017/09/26 Javascript
浅谈KOA2 Restful方式路由初探
2019/03/14 Javascript
解决vue props传Array/Object类型值,子组件报错的情况
2020/11/07 Javascript
[45:40]Ti4 冒泡赛第二天NEWBEE vs NaVi 1
2014/07/15 DOTA
Python中unittest模块做UT(单元测试)使用实例
2015/06/12 Python
linux平台使用Python制作BT种子并获取BT种子信息的方法
2017/01/20 Python
对python中的高效迭代器函数详解
2018/10/18 Python
详解Python静态网页爬取获取高清壁纸
2019/04/23 Python
Python实现非正太分布的异常值检测方式
2019/12/09 Python
python分布式计算dispy的使用详解
2019/12/22 Python
Python matplotlib画曲线例题解析
2020/02/07 Python
css3实现一个div设置多张背景图片及background-image属性实例演示
2017/08/10 HTML / CSS
html5菜单折纸效果
2014/04/22 HTML / CSS
巴西最大的家具及装饰用品店:Mobly
2017/10/11 全球购物
英国简约舒适女装品牌:Great Plains
2018/07/27 全球购物
墨尔本最受欢迎的复古风格品牌:Princess Highway
2018/12/21 全球购物
超市总经理岗位职责
2014/02/02 职场文书
小学教师培训感言
2014/02/11 职场文书
大一新生学期自我评价
2014/04/09 职场文书
工作调动申请报告
2015/05/18 职场文书
同意转租证明
2015/06/24 职场文书
2016大学生社会实践心得体会范文
2016/01/14 职场文书
在JavaScript中如何使用宏详解
2021/05/06 Javascript
解析MySQL binlog
2021/06/11 MySQL
关于JavaScript 中 if包含逗号表达式
2021/11/27 Javascript
Python使用Web框架Flask开发项目
2022/06/01 Python