nodejs typescript怎么发送get、post请求,如何获取网易云通信token
nodejs typescript怎么发送get、post请求,如何获取网易云通信token
yarn add jshashes
yarn add superagent
检查语法
yarn lint
=======================
user.imToken = await setImToken(user.id); export async function setImToken(userid: string) {
const imAppKey: string = config.get('imAppKey');
const imAppSecret: string = config.get('imAppSecret');
const imUrl: string = config.get('imUrl');
const nonce: string = Math.random().toString(36).substr(2, 15);
const timestamp: number = Date.parse(new Date().toString())/1000;
const request = require('request');
const Hashes = require('jshashes');
// 进行SHA1哈希计算,转化成16进制字符 这里用的库为jshashes
const sha1Str = imAppSecret + nonce + timestamp;
const SHA1 = new Hashes.SHA1().hex(sha1Str); const headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
'AppKey': imAppKey,
'Nonce': nonce,
'CurTime': timestamp,
'CheckSum': SHA1
};
const data = {accid: userid};
let imtoken: string;
imtoken = '';
console.log('pre get:' + imUrl);
const res: superagent.Response = await remoteUrl(imUrl, {accid: userid}, headers); if (!res.error) {
console.log('do update');
console.log('userid:' + userid);
const text = JSON.parse(res.text);
console.log('code:' + text.code);
if (text.code === 200) {
const user: UserDocument | null = await UserModel.findById(userid);
if (user) {
// await user.update({imToken: 'test'});
console.log('imToken:' + text.info.token);
imtoken = text.info.token;
await user.update({imToken: text.info.token});
}
} else {
console.log('code:' + text.code);
console.log('error:' + res.text);
} }
return imtoken;
} export async function remoteUrl(url: string, data: object, headers: object) {
return new Promise<superagent.Response>((resolve, reject) => {
superagent.post(url)
.set(headers)
.send(data)
.end((err: Error, res: superagent.Response) => {
// console.log('end url:' + url);
if (!err) {
// const info = JSON.parse(res.text);
// console.log('code:' + info.code);
resolve(res);
} else{
console.log('err:' + err);
reject(err);
}
});
});
}
user.imToken = await setImToken(user.id); export async function setImToken(userid: string) {
const imAppKey: string = config.get('imAppKey');
const imAppSecret: string = config.get('imAppSecret');
const imUrl: string = config.get('imUrl');
const nonce: string = Math.random().toString(36).substr(2, 15);
const timestamp: number = Date.parse(new Date().toString())/1000;
const request = require('request');
const Hashes = require('jshashes');
// 进行SHA1哈希计算,转化成16进制字符 这里用的库为jshashes
const sha1Str = imAppSecret + nonce + timestamp;
const SHA1 = new Hashes.SHA1().hex(sha1Str); const headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
'AppKey': imAppKey,
'Nonce': nonce,
'CurTime': timestamp,
'CheckSum': SHA1
};
const data = {accid: userid};
let imtoken: string;
imtoken = '';
console.log('pre get:' + imUrl);
const res: superagent.Response = await remoteUrl(imUrl, {accid: userid}, headers); if (!res.error) {
console.log('do update');
console.log('userid:' + userid);
const text = JSON.parse(res.text);
console.log('code:' + text.code);
if (text.code === 200) {
const user: UserDocument | null = await UserModel.findById(userid);
if (user) {
// await user.update({imToken: 'test'});
console.log('imToken:' + text.info.token);
imtoken = text.info.token;
await user.update({imToken: text.info.token});
}
} else {
console.log('code:' + text.code);
console.log('error:' + res.text);
} }
return imtoken;
} export async function remoteUrl(url: string, data: object, headers: object) {
return new Promise<superagent.Response>((resolve, reject) => {
superagent.post(url)
.set(headers)
.send(data)
.end((err: Error, res: superagent.Response) => {
// console.log('end url:' + url);
if (!err) {
// const info = JSON.parse(res.text);
// console.log('code:' + info.code);
resolve(res);
} else{
console.log('err:' + err);
reject(err);
}
});
});
}
=======================
import { expect } from 'chai';
import { setImToken } from '../../app/controllers/userController';
import { connectMongoDatabase } from '../../app/db/mongo';
import config from 'config';
const mongoUri: string = config.get('mongoUri'); describe('getImtoken test', () => {
it('Should getImtoken', async () => {
// setTimeout(done, 15000);
connectMongoDatabase(mongoUri);
const rs: string = await setImToken('5b29fcca37d16537806b1bf4');
console.log('rs=' + rs);
expect(rs).equal('');
}).timeout(8000);
});
=======================
简化版的
export async function getIMToken(accid: string) {
const { AppKey, AppSecret, AppUrl } = config.get('imCfg');
const Endpoint = '/user/create.action';
const Nonce: string = Math.random().toString(36).substr(2, 15);
const CurTime: number = Math.floor(Date.now() / 1000);
const CheckSum: string = crypto.createHash('sha1').update(AppSecret + Nonce + CurTime).digest('hex'); const headers = { AppKey, Nonce, CurTime, CheckSum };
const resp = await rp.post(AppUrl + Endpoint, { form: { accid }, headers, json: true });
try {
if (resp.code === 200 && resp.info) {
return resp.info.token;
} else {
console.warn(resp);
return null;
}
} catch (e) {
console.warn(e);
return null;
}
}
---------------------
import { getIMToken } from '../../app/controllers/userController'; describe('getIMToken test', () => {
it('Should get IMToken', async () => {
const accid = '5b2a2ba4f032150023ceec46';
const token = await getIMToken(accid);
console.log(accid, token);
});
});
测试版的:
export async function getImToken(userid: string) {
const imAppKey: string = config.get('imAppKey');
const imAppSecret: string = config.get('imAppSecret');
const imUrl: string = config.get('imUrl');
const nonce: string = Math.random().toString(36).substr(2, 15);
const timestamp: number = Date.parse(new Date().toString())/1000;
const request = require('request');
const Hashes = require('jshashes');
// 进行SHA1哈希计算,转化成16进制字符 这里用的库为jshashes
const sha1Str = imAppSecret + nonce + timestamp;
const SHA1 = new Hashes.SHA1().hex(sha1Str); const options = {
// url: imUrl,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
'AppKey': imAppKey,
'Nonce': nonce,
'CurTime': timestamp,
'CheckSum': SHA1
},
form: {
accid: userid
}
};
const headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
'AppKey': imAppKey,
'Nonce': nonce,
'CurTime': timestamp,
'CheckSum': SHA1
};
const data = {accid: userid};
let imtoken: string;
imtoken = '';
console.log('pre get:' + imUrl);
// const res: superagent.Response = await remoteUrl(imUrl, {accid: userid}, headers);
const response: superagent.Response = await new Promise<superagent.Response>((resolve, reject) => {
superagent.post(imUrl)
.set(headers)
.send(data)
.end((err: Error, res: superagent.Response) => {
console.log('end url:' + imUrl);
if (err) {
console.log('err:' + err);
imtoken = 'error noimtoken';
reject(err);
} else {
const info = JSON.parse(res.text);
if (info.code === 200) {
imtoken = info.info.token;
} else {
imtoken = info.desc;
}
console.log('code:' + info.code);
console.log('res:' + res.text);
resolve(res);
}
});
});
console.log('back res:' + response.text);
/*
const promise = new Promise<string>((resolve, reject) => {
console.log('promise:' + imUrl);
request(imUrl, options, (err: any, response: any, body: any ) => {
console.log('got:' + imUrl);
if (!err) {
body = body.toString();
console.log('bytes:' + body.length)
imtoken = body;
resolve(body);
} else {
console.log(err);
imtoken = 'noimtoken';
reject(err);
}
});
});
*/
/*
const _res: any = await new Promise((resolve, reject) => {
request(options, (parameters: { error: any, response: any, body: any }) => {
const {error: error, response, body} = parameters;
if (!error && response.statusCode === 200) {
const info = JSON.parse(body);
console.log(info);
imtoken = info.info.token;
// resolve(info);
} else {
// reject(error);
imtoken = 'noimtoken';
console.log(error);
}
});
});
*/
return imtoken;
} export async function remoteUrl(url: string, data: object, headers: object) {
return new Promise<superagent.Response>((resolve, reject) => {
superagent.post(url)
.set(headers)
.send(data)
.end((err: Error, res: superagent.Response) => {
console.log('end url:' + url);
if (!err) {
const info = JSON.parse(res.text);
console.log('code:' + info.code);
console.log('res:' + res.text);
resolve(res);
} else{
console.log('err:' + err);
reject(err);
}
});
});
}
nodejs typescript怎么发送get、post请求,如何获取网易云通信token的更多相关文章
- 转: Nodejs 发送HTTP POST请求实例
项目里面需要用到使用NodeJs来转发HTTP POST请求,把过程记录一下: exports.sendEmail = function (req, res) { res.send(200, req. ...
- 关于nodejs能同时接受多少个请求的问题?////zzz
关于nodejs能同时接受多少个请求的问题? 最近学习node,看了很多教程,都在赞扬nodejs的异步I/O,异步I/O的特点就是,每接收一个请求,使用异步调用处理请求,不用等待结果,可以继续运行其 ...
- 使用Typescript重构axios(十六)——请求和响应数据配置化
0. 系列文章 1.使用Typescript重构axios(一)--写在最前面 2.使用Typescript重构axios(二)--项目起手,跑通流程 3.使用Typescript重构axios(三) ...
- 使用Typescript重构axios(十九)——请求取消功能:实现第二种使用方式
0. 系列文章 1.使用Typescript重构axios(一)--写在最前面 2.使用Typescript重构axios(二)--项目起手,跑通流程 3.使用Typescript重构axios(三) ...
- 使用Typescript重构axios(二十)——请求取消功能:实现第一种使用方式
0. 系列文章 1.使用Typescript重构axios(一)--写在最前面 2.使用Typescript重构axios(二)--项目起手,跑通流程 3.使用Typescript重构axios(三) ...
- nodejs 中 接受前端的数据请求的处理
前台 ----> 后台 后台要接受 前台的数据,只能通过 http 但是 前台接受 后台的数据有 from ajax jsonp nodejs 给我们提供了模块 url 模块,可以 ...
- 如果调用ASP.NET Web API不能发送PUT/DELETE请求怎么办?
理想的RESTful Web API采用面向资源的架构,并使用请求的HTTP方法表示针对目标资源的操作类型.但是理想和现实是有距离的,虽然HTTP协议提供了一系列原生的HTTP方法,但是在具体的网络环 ...
- 调用webapi 错误:使用 HTTP 谓词 POST 向虚拟目录发送了一个请求,而默认文档是不支持 GET 或 HEAD 以外的 HTTP 谓词的静态文件。的解决方案
第一次调用webapi出错如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http:// ...
- iOS 发送请求时获取cookie
Cookie: 记录者用户信息的保存在本地的用户数据,如果有会被自动附上 值得一提的是,在iOS中当你发送一个任意请求时,不管你愿不愿意,NSURLRequest都会自动帮你记录你所访问的URL上设置 ...
随机推荐
- Docker 容器(六)
镜像(Image)和容器(Container)的关系,就像是面向对象程序设计中的 类 和 实例 一样,镜像是静态的定义,容器是镜像运行时的实体.容器可以被创建.启动.停止.删除.暂停等. 容器的实质是 ...
- python的队列和栈
(一)队列和栈的区别 1.队列: 队列是一种特殊的线性表.其两头都有限制,插入只能在表的一端进行(只进不出),而删除只能在表的另一端进行(只出不进),允许删除的一端称为队尾(rear),允许插入的一端 ...
- (1.13)mysql优化数据库对象
(1.13)mysql优化数据库对象 1.mysql优化数据库对象 [1.1]数据库对象类型优化 select * from test1 procedure analyse(); ,); --不要为那 ...
- cd 命令
[root@localhost ~]# cd # 进入当前用户的家目录 [root@localhost ~]# cd ~ # 进入当前用户的家目录 [root@localhost ~]# cd /da ...
- Python统计日志中每个IP出现次数
介绍了Python统计日志中每个IP出现次数的方法,实例分析了Python基于正则表达式解析日志文件的相关技巧,需要的朋友可以参考下 本脚本可用于多种日志类型 #-*- coding:utf-8 -* ...
- 初识Shell与Shell脚本
初识Shell Shell 是一个用 C 语言编写的程序,Shell 既是一种命令语言,又是一种程序设计语言. Shell 是指一种应用程序,这个应用程序提供了一个界面,用户通过这个界面访问操作系统内 ...
- 014-并发编程-java.util.concurrent之-CountDownLatch
一.概述 CountDownLatch是JAVA提供在java.util.concurrent包下的一个辅助类,指定的一个或多个线程等待其他线程执行完成后执行. 能够使一个线程等待其他线程完成各自的工 ...
- eclipse 优化
1.取消验证 windows–>perferences–>validation 把 除了manual 下面的全部点掉,build下只留 classpath dependency Valid ...
- 列表 list 容器类型数据(str字符串, list列表, tuple元组, set集合, dict字典)--->元组 tuple-->字符串 str
# ### 列表 list 容器类型数据(str字符串, list列表, tuple元组, set集合, dict字典) # (1)定义一个列表 listvar = [] print(listvar, ...
- ngx_lua 模块详细讲解(基于openresty)
ngx_lua模块的原理: 1.每个worker(工作进程)创建一个Lua VM,worker内所有协程共享VM:2.将Nginx I/O原语封装后注入 Lua VM,允许Lua代码直接访问:3.每个 ...