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极简入门教程(二):定时器
Oct 25 NodeJs
nodejs实现bigpipe异步加载页面方案
Jan 26 NodeJs
nodeJs爬虫获取数据简单实现代码
Mar 29 NodeJs
nodejs简单实现操作arduino
Sep 25 NodeJs
nodejs开发——express路由与中间件
Mar 24 NodeJs
nodejs使用express创建一个简单web应用
Mar 31 NodeJs
nodejs async异步常用函数总结(推荐)
Nov 17 NodeJs
nodejs更改项目端口号的方法
May 13 NodeJs
nodejs异步编程基础之回调函数用法分析
Dec 26 NodeJs
nodejs实现获取本地文件夹下图片信息功能示例
Jun 22 NodeJs
nodejs 递归拷贝、读取目录下所有文件和目录
Jul 18 NodeJs
Nodejs监听日志文件的变化的过程解析
Aug 04 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使用缓存即时输出内容(output buffering)的方法
2015/08/03 PHP
PHP时间处理类操作示例
2018/09/05 PHP
可以用来调试JavaScript错误的解决方案
2010/08/07 Javascript
20款非常优秀的 jQuery 工具提示插件 推荐
2012/07/15 Javascript
鼠标放在图片上显示大图的JS代码
2013/03/26 Javascript
js相册效果代码(点击创建即可)
2013/04/16 Javascript
javascript 数组排序函数sort和reverse使用介绍
2013/11/21 Javascript
jquery改变disabled的boolean状态的三种方法
2013/12/13 Javascript
JavaScript合并两个数组并去除重复项的方法
2015/06/13 Javascript
jQuery基于扩展实现的倒计时效果
2016/05/14 Javascript
浅谈jquery.form.js的ajaxSubmit和ajaxForm的使用
2016/09/09 Javascript
详解javascript表单的Ajax提交插件的使用
2016/12/29 Javascript
Vuex 使用 v-model 配合 state的方法
2018/11/13 Javascript
vue中格式化时间过滤器代码实例
2019/04/17 Javascript
详解Python中time()方法的使用的教程
2015/05/22 Python
基于python实现微信模板消息
2015/12/21 Python
Python的包管理器pip更换软件源的方法详解
2016/06/20 Python
Python爬取APP下载链接的实现方法
2016/09/30 Python
将字典转换为DataFrame并进行频次统计的方法
2018/04/08 Python
Python针对给定列表中元素进行翻转操作的方法分析
2018/04/27 Python
Django读取Mysql数据并显示在前端的实例
2018/05/27 Python
mvc框架打造笔记之wsgi协议的优缺点以及接口实现
2018/08/01 Python
django将网络中的图片,保存成model中的ImageField的实例
2019/08/07 Python
ubuntu 18.04 安装opencv3.4.5的教程(图解)
2019/11/04 Python
python实现查找所有程序的安装信息
2020/02/18 Python
Python应用实现处理excel数据过程解析
2020/06/19 Python
如何教少儿学习Python编程
2020/07/10 Python
python高级特性简介
2020/08/13 Python
IE兼容css3圆角的实现代码
2011/07/21 HTML / CSS
什么是测试驱动开发(TDD)
2012/02/15 面试题
毕业生自我鉴定实例
2014/01/21 职场文书
主管竞聘书范文
2014/03/31 职场文书
网聊搭讪开场白
2015/05/28 职场文书
人生遥控器观后感
2015/06/11 职场文书
导游词之舟山普陀山
2019/11/06 职场文书
MyBatis自定义SQL拦截器示例详解
2021/10/24 Java/Android