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 相关文章推荐
Windows 系统下设置Nodejs NPM全局路径
Apr 26 NodeJs
nodejs 的 session 简单使用
Jun 06 NodeJs
Nodejs中解决cluster模块的多进程如何共享数据问题
Nov 10 NodeJs
Highcharts+NodeJS搭建数据可视化平台示例
Jan 01 NodeJs
NodeJS仿WebApi路由示例
Feb 28 NodeJs
async/await与promise(nodejs中的异步操作问题)
Mar 03 NodeJs
详解nodejs微信公众号开发——2.自动回复
Apr 10 NodeJs
nodejs入门教程三:调用内部和外部方法示例
Apr 24 NodeJs
Nodejs模块载入运行原理
Feb 23 NodeJs
nodejs 简单实现动态html的方法
May 12 NodeJs
Nodejs中的require函数的具体使用方法
Apr 02 NodeJs
浅谈JS和Nodejs中的事件驱动
May 05 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 生成N个不重复的随机数
2015/01/21 PHP
JavaScript中数组对象的那些自带方法介绍
2013/03/12 Javascript
Jquery操作Ajax方法小结
2015/11/29 Javascript
基于BootStrap Metronic开发框架经验小结【二】列表分页处理和插件JSTree的使用
2016/05/12 Javascript
关于input全选反选恶心的异常情况
2016/07/24 Javascript
微信小程序 教程之事件
2016/10/18 Javascript
Angular中$state.go页面跳转并传递参数的方法
2017/05/09 Javascript
关于在mongoose中填充外键的方法详解
2017/08/14 Javascript
element-ui循环显示radio控件信息的方法
2018/08/24 Javascript
React 源码中的依赖注入方法
2018/11/07 Javascript
JavaScript错误处理操作实例详解
2019/01/04 Javascript
Vue中全局变量的定义和使用
2019/06/05 Javascript
[01:13:51]TNC vs Serenity 2018国际邀请赛小组赛BO2 第二场 8.18
2018/08/19 DOTA
python查找指定具有相同内容文件的方法
2015/06/28 Python
浅谈Python中函数的参数传递
2016/06/21 Python
python中多个装饰器的执行顺序详解
2018/10/08 Python
Python  Django 母版和继承解析
2019/08/09 Python
Python tkinter三种布局实例详解
2020/01/06 Python
Pytorch 保存模型生成图片方式
2020/01/10 Python
python中元组的用法整理
2020/06/15 Python
详解python中的lambda与sorted函数
2020/09/04 Python
python 生成正态分布数据,并绘图和解析
2020/12/21 Python
实体的生命周期
2013/08/31 面试题
房地产销售经理岗位职责
2014/01/01 职场文书
兽医医药专业求职信
2014/07/27 职场文书
争做文明公民倡议书
2014/08/29 职场文书
售房委托书
2014/08/30 职场文书
领导班子作风建设剖析材料
2014/10/11 职场文书
2014年超市员工工作总结
2014/11/18 职场文书
拾金不昧感谢信范文
2015/01/21 职场文书
高中运动会前导词
2015/07/20 职场文书
高中美术教学反思
2016/02/17 职场文书
2016见义勇为事迹材料汇总
2016/03/01 职场文书
教你利用Nginx 服务搭建子域环境提升二维地图加载性能的步骤
2021/09/25 Servers
python lambda 表达式形式分析
2022/04/03 Python
Python使用PyYAML库读写yaml文件的方法
2022/04/06 Python