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的更多相关文章

  1. 转: Nodejs 发送HTTP POST请求实例

    项目里面需要用到使用NodeJs来转发HTTP POST请求,把过程记录一下: exports.sendEmail = function (req, res) { res.send(200, req. ...

  2. 关于nodejs能同时接受多少个请求的问题?////zzz

    关于nodejs能同时接受多少个请求的问题? 最近学习node,看了很多教程,都在赞扬nodejs的异步I/O,异步I/O的特点就是,每接收一个请求,使用异步调用处理请求,不用等待结果,可以继续运行其 ...

  3. 使用Typescript重构axios(十六)——请求和响应数据配置化

    0. 系列文章 1.使用Typescript重构axios(一)--写在最前面 2.使用Typescript重构axios(二)--项目起手,跑通流程 3.使用Typescript重构axios(三) ...

  4. 使用Typescript重构axios(十九)——请求取消功能:实现第二种使用方式

    0. 系列文章 1.使用Typescript重构axios(一)--写在最前面 2.使用Typescript重构axios(二)--项目起手,跑通流程 3.使用Typescript重构axios(三) ...

  5. 使用Typescript重构axios(二十)——请求取消功能:实现第一种使用方式

    0. 系列文章 1.使用Typescript重构axios(一)--写在最前面 2.使用Typescript重构axios(二)--项目起手,跑通流程 3.使用Typescript重构axios(三) ...

  6. nodejs 中 接受前端的数据请求的处理

    前台 ---->  后台 后台要接受 前台的数据,只能通过 http 但是 前台接受 后台的数据有  from   ajax    jsonp nodejs 给我们提供了模块 url 模块,可以 ...

  7. 如果调用ASP.NET Web API不能发送PUT/DELETE请求怎么办?

    理想的RESTful Web API采用面向资源的架构,并使用请求的HTTP方法表示针对目标资源的操作类型.但是理想和现实是有距离的,虽然HTTP协议提供了一系列原生的HTTP方法,但是在具体的网络环 ...

  8. 调用webapi 错误:使用 HTTP 谓词 POST 向虚拟目录发送了一个请求,而默认文档是不支持 GET 或 HEAD 以外的 HTTP 谓词的静态文件。的解决方案

    第一次调用webapi出错如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http:// ...

  9. iOS 发送请求时获取cookie

    Cookie: 记录者用户信息的保存在本地的用户数据,如果有会被自动附上 值得一提的是,在iOS中当你发送一个任意请求时,不管你愿不愿意,NSURLRequest都会自动帮你记录你所访问的URL上设置 ...

随机推荐

  1. 【托业】【新托业TOEIC新题型真题】学习笔记2-题库一-->P5-6

    P5-6 --------------------------------------单词-------------------------------------- transfrom 转化 jus ...

  2. Linux dmidecode 命令

    当我们需要获取机器硬件信息时,可使用linux系统自带的dmidecode工具进行查询. dmidecode 用于获取服务器的硬件信息,通常是在不打开计算机机箱的情况下使用该命令来查找硬件详细信息 这 ...

  3. MongoDB update修改器: 针对Arrays的$修改器 $push $pull $pop

    针对Arrays的$修改器 $push : { $push: { key: value } } 它是用来对Array (list)数据类型进行 增加 新元素的,相当于我们Python中 list.ap ...

  4. Cookie和Session的区别?

    1.Cookie和Session都是会话技术,Cookie是运行在客户端,Session是运行在服务器端.      2.Cookie有大小限制以及浏览器在存cookie的个数也有限制,Session ...

  5. Python3学习之路~6.2 实例演示面向对象编程的好处

    首先建一个dog类,实例化为3个dog对象,并让它们都叫. class Dog: def bulk(self): print("xiaohuang:wang wang wang !" ...

  6. vue 后退不刷新页面

    使用 this.$router.push({path: '/aichat'})路由跳转方式跳转页面 要实现 home => chat  chat页面刷新: chat => report, ...

  7. nohup 详解

    转:https://www.cnblogs.com/jinxiao-pu/p/9131057.html nohup nohup 命令运行由 Command参数和任何相关的 Arg参数指定的命令,忽略所 ...

  8. maxcompute笔记

    maxcompute安装和配置 https://help.aliyun.com/document_detail/27804.html?spm=a2c4g.11174283.3.5.566a590e0P ...

  9. @Value("#{}") 和 @Value("{}")

    1 @Value("#{}")   SpEL表达式 @Value("#{}") 表示SpEl表达式通常用来获取bean的属性,或者调用bean的某个方法.当然还 ...

  10. java面试中经常会被问到分布式面试题

    1.Dubbo的底层实现原理和机制 –高性能和透明化的RPC远程服务调用方案 –SOA服务治理方案 Dubbo缺省协议采用单一长连接和NIO异步通讯, 适合于小数据量大并发的服务调用,以及服务消费者机 ...