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上设置 ...
随机推荐
- python-面向对象-05_面向对象封装案例 II
面向对象封装案例 II 目标 士兵突击案例 身份运算符 封装 封装 是面向对象编程的一大特点 面向对象编程的 第一步 —— 将 属性 和 方法 封装 到一个抽象的 类 中 外界 使用 类 创建 对象, ...
- (5.1)sql server系统数据库
关键词:mssql系统数据库,sql server系统数据库,tempdb的作用 master:它包含一个系统表集合,是整个实例的中央存储库,维护登录账户,其他数据库,文件分布,系统配置设置,磁盘空间 ...
- WordPress禁用插件另类方法不用进后台
刚刚一小美女说她在WordPress后台启用了一个插件后出现了问题,网站前端和后端都不能打开了,ytkah查看了一下是有个插件api和另一个插件冲突了,但要怎么禁用呢?有两个办法可以解决 1.直接删除 ...
- wordpress如何屏蔽wp-json(禁用REST API)
最近网友问ytkah怎么在网站日志文件中发现蜘蛛爬行了很多次的/wp-json/目录,在robots文件中disallow掉了爬虫还是访问了那个目录,能不能直接在程序中直接改呢?通过查询相关文档发现W ...
- Android支持全面屏设置
在AndroidManifest的application里面设置resizeableActivity的属性为true <application android:name=".Compl ...
- NginxI/O模型理论基础
I/O模型介绍 同步IO 关注的是消息通信机制 调用者需要等待被调用者先执行完毕才能往下继续执行 被调用者在执行完自己的任务后并不会同之调用者执行结果需要调用者自己去获取被调用者的执行状态 异步 ...
- python 字符串、列表和元祖之间的切换
>>> s=['http','://','www','baidu','.com'] >>> url=''.join(s) >>> url 'htt ...
- component 理解
1: sap中的component理解 component分为 genil component 和ui component component相当于整个应用中某一小块的前台/后台所有的东西都包括进去. ...
- Jsp与Servlet面试题
一.jsp有哪些内置对象作用分别是什么 答:JSP共有以下9种基本内置组件(可与ASP的6种内部组件相对应): request 用户端请求,此请求会包含来自GET/POST请求的参数 respo ...
- (转)EOSIO开发(三)钱包、账户与账户权限之概念篇
这篇文章为大家介绍钱包(Wallet).账户(Accounts).账户权限(Account authorities)的概念. 钱包 Wallet 钱包是一个本地客户端软件,有下面两个作用: 保存私钥. ...