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安装及环境配置
Jan 08 NodeJs
nodejs基础应用
Feb 03 NodeJs
用nodeJS搭建本地文件服务器的几种方法小结
Mar 16 NodeJs
nodejs实现邮件发送服务实例分享
Mar 29 NodeJs
详解如何在NodeJS项目中优雅的使用ES6
Apr 22 NodeJs
Nodejs调用WebService的示例代码
Sep 29 NodeJs
详解IWinter 一个路由转控制器的 Nodejs 库
Nov 15 NodeJs
NodeJS安装图文教程
Apr 19 NodeJs
nodejs之koa2请求示例(GET,POST)
Aug 07 NodeJs
Nodejs实现的操作MongoDB数据库功能完整示例
Feb 02 NodeJs
监控Nodejs的性能实例代码
Jul 02 NodeJs
NodeJS有难度的面试题(能答对几个)
Oct 09 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 日期和时间的处理-郑阿奇(续)
2011/07/04 PHP
PHP内核介绍及扩展开发指南―基础知识
2011/09/11 PHP
php获取目录所有文件并将结果保存到数组(实例)
2013/10/25 PHP
php之Smarty模板使用方法示例详解
2014/07/08 PHP
linux下为php添加iconv模块的方法
2016/02/28 PHP
JS判断表单输入是否为空(示例代码)
2013/12/23 Javascript
删除javascript所创建子节点的方法
2015/05/21 Javascript
动态加载js、css的实例代码
2016/05/26 Javascript
AngularJS控制器之间的通信方式详解
2016/11/03 Javascript
vue2实现移动端上传、预览、压缩图片解决拍照旋转问题
2017/04/13 Javascript
AngularJS实现动态切换样式的方法分析
2018/06/26 Javascript
微信小程序日历组件使用方法详解
2018/12/29 Javascript
Vue 引入AMap高德地图的实现代码
2019/04/29 Javascript
在vue中实现给每个页面顶部设置title
2020/07/29 Javascript
Vuejs通过拖动改变元素宽度实现自适应
2020/09/02 Javascript
基于Python实现通过微信搜索功能查看谁把你删除了
2016/01/27 Python
django 解决manage.py migrate无效的问题
2018/05/27 Python
Ubuntu下升级 python3.7.1流程备忘(推荐)
2018/12/10 Python
对python多线程中互斥锁Threading.Lock的简单应用详解
2019/01/11 Python
解决在pycharm中显示额外的 figure 窗口问题
2019/01/15 Python
Python实现的企业粉丝抽奖功能示例
2019/07/26 Python
Python3 pywin32模块安装的详细步骤
2020/05/26 Python
python 爬虫如何正确的使用cookie
2020/10/27 Python
canvas像素点操作之视频绿幕抠图
2018/09/11 HTML / CSS
专门出售各种儿童读物的网站:Put Me In The Story
2016/08/07 全球购物
领班岗位职责范文
2014/02/06 职场文书
销售员个人求职的自我评价
2014/02/10 职场文书
双语教学实施方案
2014/03/23 职场文书
校运会口号
2014/06/18 职场文书
校长四风对照检查材料
2014/09/27 职场文书
村党支部对照检查材料思想汇报
2014/09/28 职场文书
2014年酒店工作总结范文
2014/11/17 职场文书
英雄儿女观后感
2015/06/09 职场文书
鲁滨逊漂流记读书笔记
2015/06/26 职场文书
python spilt()分隔字符串的实现示例
2021/05/21 Python
SpringBoot集成MongoDB实现文件上传的步骤
2022/04/18 MongoDB