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. C++中类的前向声明

    概念 可以声明一个类而不是定义它; class Screen; 这个声明被称为"前向声明".在声明之后,定义之前,类screen是一个不完全类型,即已知Screen是一个类型,但不 ...

  2. abap中结构体嵌套结构体。

    1: 结构体中嵌套结构体. *&---------------------------------------------------------------------* *& Re ...

  3. [sh]getopt参数解析

    https://www.cnblogs.com/FrankTan/archive/2010/03/01/1634516.html sh参数处理方法 * 手工处理方式 * getopts #好像不支持长 ...

  4. 根据构建类型动态设置AndroidManifest.xml文件中的meta-data

    当debug和release版本使用不同的值时,使用Gradle设置相应的值. Android主配置文件 <meta-data android:name="com.amap.api.v ...

  5. 无法连接 MKS:套接字连接尝试次数太多正在放弃

    我的电脑 -> 右键 -> 管理 -> 服务和应用程序 -> 服务: 开启下面的服务: 服务启动成功后,重启虚拟机; 或者先挂起虚拟机,等服务启动后,继续运行挂起的虚拟机:

  6. k8s 健康检查

    livenessProbe: exec: command: - /bin/sh - '-c' - /opt/app-root/src/check_conf.sh failureThreshold: 3 ...

  7. js动态规划---最少硬币找零问题

    给定钱币的面值 1.5.10.25 需要找给客户 36 最少找零数为: 1.10.25 function MinCoinChange(coins){ var coins = coins; var ca ...

  8. 工作流引擎--swamp

    什么是工作流引擎(Workflow Engine )   例如开发一个系统最关键的部分不是系统的界面,也不是和数据库之间的信息交换,而是如何根据业务逻辑开发出符合实际需要的程序逻辑并确保其稳定性.易维 ...

  9. 闪存卡被创建pv报错

    背景:某机器有2块闪存卡,利用LVM,将其挂载到一个目录供测试使用: 之前厂商已经安装了闪存卡对应的驱动,fdisk可以看到闪存卡信息,但是在pvcreate创建时,遭遇如下错误: # pvcreat ...

  10. spring mvc配置datasource数据源的三种方式

    2.使用org.apache.commons.dbcp.BasicDataSource 说明:这是一种推荐说明的数据源配置方式,它真正使用了连接池技术 <bean id="dataSo ...