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的require模块(文件模块/核心模块)及路径介绍
Jan 14 NodeJs
Windows系统下使用Sublime搭建nodejs环境
Apr 13 NodeJs
Nodejs进阶:如何将图片转成datauri嵌入到网页中去实例
Nov 21 NodeJs
nodejs和php实现图片访问实时处理
Jan 05 NodeJs
nodejs中使用HTTP分块响应和定时器示例代码
Mar 19 NodeJs
详解nodejs微信公众号开发——1.接入微信公众号
Apr 10 NodeJs
nodejs简单实现TCP服务器端和客户端的聊天功能示例
Jan 04 NodeJs
nodejs读取并去重excel文件
Apr 22 NodeJs
详解Nodejs get获取远程服务器接口数据
Mar 26 NodeJs
nodejs实现获取本地文件夹下图片信息功能示例
Jun 22 NodeJs
纯异步nodejs文件夹(目录)复制功能
Sep 03 NodeJs
windows如何把已安装的nodejs高版本降级为低版本(图文教程)
Dec 14 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数组操作简单案例分析
2016/10/15 PHP
PHP 二维关联数组根据其中一个字段排序(推荐)
2017/04/04 PHP
Laravel框架下载,安装及路由操作图文详解
2019/12/04 PHP
PHP如何通过date() 函数格式化显示时间
2020/11/13 PHP
js replace正则表达式应用案例讲解
2013/01/17 Javascript
js window.open弹出新的网页窗口
2014/01/16 Javascript
jquery隔行换色效果实现方法
2015/01/15 Javascript
JavaScript判断对象是否为数组
2015/12/22 Javascript
yarn的使用与升级Node.js的方法详解
2017/06/04 Javascript
JS实现获取毫秒值及转换成年月日时分秒的方法
2018/08/15 Javascript
小程序实现人脸识别功能(百度ai)
2018/12/23 Javascript
jQuery实现当拉动滚动条到底部加载数据的方法分析
2019/01/24 jQuery
少女风vue组件库的制作全过程
2019/05/15 Javascript
微信小程序调用wx.getImageInfo遇到的坑解决
2020/05/31 Javascript
python实现的简单RPG游戏流程实例
2015/06/28 Python
Python使用gensim计算文档相似性
2016/04/10 Python
Python的requests网络编程包使用教程
2016/07/11 Python
在django admin中添加自定义视图的例子
2019/07/26 Python
python读取大文件越来越慢的原因与解决
2019/08/08 Python
python 批量修改 labelImg 生成的xml文件的方法
2019/09/09 Python
python通过实例讲解反射机制
2019/10/17 Python
python模拟实现斗地主发牌
2020/01/07 Python
Python3列表List入门知识附实例
2020/02/09 Python
python误差棒图errorbar()函数实例解析
2020/02/11 Python
基于python实现可视化生成二维码工具
2020/07/08 Python
用CSS3的box-reflect来制作倒影效果
2016/11/15 HTML / CSS
HTML5的download属性详细介绍和使用实例
2014/04/23 HTML / CSS
使用phonegap创建联系人的实现方法
2017/03/30 HTML / CSS
财务会计人员岗位职责
2013/11/30 职场文书
《桂林山水》教学反思
2014/02/08 职场文书
优秀语文教师事迹
2014/05/18 职场文书
领导欢迎词致辞
2015/01/23 职场文书
党员反腐倡廉学习心得体会
2015/08/15 职场文书
详解redis分布式锁的这些坑
2021/05/19 Redis
Python Django框架介绍之模板标签及模板的继承
2021/05/27 Python
如何判断pytorch是否支持GPU加速
2021/06/01 Python