• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

nodejstypescript怎么发送get、post请求,如何获取网易云通信token

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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);
                }
            });
    });
}

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
基于TypeScript的Angular6.X系列学习笔记-简介发布时间:2022-07-18
下一篇:
TypeScript设计模式之组合、享元发布时间:2022-07-18
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap