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使用mysql模块之获得更新和删除影响的行数的方法
Mar 18 NodeJs
轻松创建nodejs服务器(10):处理上传图片
Dec 18 NodeJs
nodejs使用express创建一个简单web应用
Mar 31 NodeJs
详解nodejs微信公众号开发——6.自定义菜单
Apr 13 NodeJs
详解如何在NodeJS项目中优雅的使用ES6
Apr 22 NodeJs
Nodejs回调加超时限制两种实现方法
Jun 09 NodeJs
nodejs async异步常用函数总结(推荐)
Nov 17 NodeJs
nodejs实现连接mongodb数据库的方法示例
Mar 15 NodeJs
nodejs遍历文件夹下并操作HTML/CSS/JS/PNG/JPG的方法
Nov 01 NodeJs
nodejs 使用http进行post或get请求的实例(携带cookie)
Jan 03 NodeJs
独立部署小程序基于nodejs的服务器过程详解
Jun 24 NodeJs
Nodejs环境实现socket通信过程解析
Jul 03 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模板函数 正则实现代码
2012/10/15 PHP
JavaScript入门教程(6) Window窗口对象
2009/01/31 Javascript
动态样式类封装JS代码
2009/09/02 Javascript
JQuery上传插件Uploadify使用详解及错误处理
2010/04/27 Javascript
Jquery ThickBox插件使用心得(不建议使用)
2010/09/08 Javascript
jqPlot 图表中文API使用文档及源码和在线示例
2012/02/07 Javascript
caller和callee的区别介绍及演示结果
2013/03/10 Javascript
jQuery插件Skippr实现焦点图幻灯片特效
2015/04/12 Javascript
javascript实现table表格隔行变色的方法
2015/05/13 Javascript
浅谈JavaScript前端开发的MVC结构与MVVM结构
2016/06/03 Javascript
AngularJS基础 ng-submit 指令简单示例
2016/08/03 Javascript
ionic开发中点击input时键盘自动弹出
2016/12/23 Javascript
从零开始学习Node.js系列教程之基于connect和express框架的多页面实现数学运算示例
2017/04/13 Javascript
bootstrap-table实现服务器分页的示例 (spring 后台)
2017/09/01 Javascript
js时间戳与日期格式之间转换详解
2017/12/11 Javascript
vue-cli脚手架引入弹出层layer插件的几种方法
2019/06/24 Javascript
详谈vue中router-link和传统a链接的区别
2020/07/22 Javascript
Postman环境变量全局变量使用方法详解
2020/08/13 Javascript
[00:15]TI9地铁玩家打卡
2019/08/11 DOTA
python爬虫爬取快手视频多线程下载功能
2018/02/28 Python
python使用numpy读取、保存txt数据的实例
2018/10/14 Python
Python使用python-docx读写word文档
2019/08/26 Python
python pyenv多版本管理工具的使用
2019/12/23 Python
Python如何爬取b站热门视频并导入Excel
2020/08/10 Python
Django自带的用户验证系统实现
2020/12/18 Python
Android interview questions
2016/12/25 面试题
EJB包括(SessionBean,EntityBean)说出他们的生命周期,及如何管理事务的?
2013/02/17 面试题
初中生三年学习生活的自我评价
2013/11/03 职场文书
工程管理专业个人求职信范文
2013/12/07 职场文书
厂长助理岗位职责
2013/12/27 职场文书
生产车间班组长岗位职责
2014/01/06 职场文书
致标枪运动员广播稿
2014/02/06 职场文书
小学安全教育材料
2014/02/17 职场文书
学雷锋志愿服务月活动总结
2014/03/09 职场文书
单位实习鉴定评语
2015/01/04 职场文书
仙境之桥观后感
2015/06/16 职场文书