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实现黑名单中间件设计
Jun 17 NodeJs
nodejs实现获取某宝商品分类
May 28 NodeJs
用nodejs的实现原理和搭建服务器(动态)
Aug 10 NodeJs
解决nodejs中使用http请求返回值为html时乱码的问题
Feb 18 NodeJs
nodejs6下使用koa2框架实例
May 18 NodeJs
NodeJs使用Mysql模块实现事务处理实例
May 31 NodeJs
nodejs body-parser 解析post数据实例
Jul 26 NodeJs
nodejs之get/post请求的几种方式小结
Jul 26 NodeJs
基于nodejs的雪碧图制作工具的示例代码
Nov 05 NodeJs
nodejs基础之多进程实例详解
Dec 27 NodeJs
nodejs分离html文件里面的js和css的方法
Apr 09 NodeJs
nodejs实现日志读取、日志查找及日志刷新的方法分析
May 20 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 格式化数字的时候注意数字的范围
2010/04/13 PHP
php设计模式 Prototype (原型模式)代码
2011/06/26 PHP
163的邮件用phpmailer发送(实例详解)
2013/06/24 PHP
Yii2中SqlDataProvider用法示例
2016/09/22 PHP
laravel 获取当前url的别名方法
2019/10/11 PHP
jQuery prev ~ siblings选择器使用介绍
2013/08/09 Javascript
php的文件上传入门教程(实例讲解)
2014/04/10 Javascript
jQuery源码解读之removeAttr()方法分析
2015/02/20 Javascript
jquery实现表单输入时提示文字滑动向上效果
2015/08/10 Javascript
jquery实现邮箱自动填充提示功能
2015/11/17 Javascript
AngularJS使用ng-repeat和ng-if实现数据的删选显示效果示例【适用于表单数据的显示】
2016/12/13 Javascript
详解vue.js的事件处理器v-on:click
2017/06/27 Javascript
vue+vux实现移动端文件上传样式
2017/07/28 Javascript
jquery学习笔记之无new构建详解
2017/12/07 jQuery
Vue 中mixin 的用法详解
2018/04/23 Javascript
你点的 ES6一些小技巧,请查收
2018/04/25 Javascript
vue组件中的数据传递方法
2018/05/14 Javascript
小程序实现抽奖动画
2020/04/16 Javascript
JavaScript中条件语句的优化技巧总结
2020/12/04 Javascript
跟老齐学Python之复习if语句
2014/10/02 Python
详解django中自定义标签和过滤器
2017/07/03 Python
python实现二维数组的对角线遍历
2019/03/02 Python
如何在python中执行另一个py文件
2020/04/30 Python
什么是Python中的匿名函数
2020/06/02 Python
Python3读写ini配置文件的示例
2020/11/06 Python
python FTP编程基础入门
2021/02/27 Python
HTML5中语义化 b 和 i 标签
2008/10/17 HTML / CSS
澳大利亚当地最大的时装生产商:Cue
2018/08/06 全球购物
开学季活动策划方案
2014/02/28 职场文书
幼儿园见习报告
2014/10/30 职场文书
2014年图书馆工作总结
2014/11/25 职场文书
运动员入场前导词
2015/07/20 职场文书
Python初学者必备的文件读写指南
2021/06/23 Python
ObjectMapper 如何忽略字段大小写
2021/06/29 Java/Android
使用python绘制横竖条形图
2022/04/21 Python
python playwrigh框架入门安装使用
2022/07/23 Python