TypeScript后端http请求

最近在做vscode插件,需要发送http请求,常用的那些像ajax和jquery似乎在这个半后端性质的项目里用不上,只能再找合适的方法,下面分享两种方法,根据我的使用需要更喜欢第二种。

request方法

链接: https://github.com/request/request

用的方式也比较简单,npm install request 安装一下,分享一个基本例子:

里面的链接简单打了一下码。

/**

* 登录函数,旧版登录函数,无法返回信息

* @param user 用户名

* @param pwd 密码

*/

static login(user:string,pwd:string){

const formData = {

"username": user,

"password": pwd,

"client_id": "L******P",

"client_secret": "secret",

"scope": "all",

"grant_type": "password"

};

request.post({url:'https://***.test.ti*****k.cn/oauth/token', formData: formData}, (err, httpResponse, body) =>{

if (err) {

window.showInformationMessage('登录失败!');

return console.error('upload failed:', err);

}

let data = JSON.parse(body);

let token:string = data.access_token;

let uid:string = data.uid;

console.log(data);

if(data.code == '400'){

window.showInformationMessage("登录失败!账号或密码错误");

}

else {

window.showInformationMessage("登录成功!");

L******b.getExperimentByToken(token);

Gitee.getGiteeByToken(token,uid);

commands.executeCommand('webide.test');

commands.executeCommand('webide.burnRefresh');

}

});

}

传参数比较方便,以上是post方法例子,get方法也一样。

缺点:我没有找到可以处理这个异步返回的方法,并且数据无法通过返回函数获得,里面的回调函数会处理获取的结果却没法把数据仍出来。

fetch方法

链接: https://github.com/node-fetch/node-fetch

安装:npm install node-fetch 引入:import fetch from ‘node-fetch’;

使用例子:依然是刚才的登录场景:

/**

* 新版登录函数

* @param user 用户信息对象

* @returns 带token的用户对象 | 无token对象

*/

static async loginTest(user:L*****ser):Promise{

const params = new URLSearchParams();

params.append("username",user.userName);

params.append("password",user.passWord);

params.append("client_id", "L******P");

params.append("client_secret", "secret");

params.append("scope", "all");

params.append("grant_type", "password");

let data = await fetch('https://***.test.ti*****k.cn/oauth/token', {

method: 'post',

body: params

}).then(async res=>JSON.parse(await res.text()));

console.log(data);

if(data.code == '400'){

window.showInformationMessage("登录失败!账号或密码错误");

return user;

}

user.setToken(data.access_token as string);

user.setUid(data.uid);

return user;

}

优点就是可以处理异步操作,并且可以通过返回获得数据。

fetch方法中不支持直接传递json参数,需要使用URLSearchParams()对象。

method默认方法为get,在get方法下不支持body参数,解决方法可以把参数放到url中比如:

/**

* 通过giteeNode获取文件内容

* @param gitNode gitee信息节点

* @returns context

*/

static async getBlobByGiteeNode(gitNode:GiteeFileNode){

const header = {

"Authorization":"Bearer "+gitNode.token,

"Content-Type": "application/json; charset=UTF-8"

};

let content = await fetch(`https://gitee.com/api/v5/repos/${gitNode.owner}/${gitNode.repo}/git/blobs/${gitNode.sha}`,{

headers:header

}).then(async res=>{

// console.log(res);

let context = JSON.parse(await res.text());

// console.log(context);

context = Buffer.from(context.content,"base64").toString('utf-8');

return context;

});

return content;

}

如果部分接口必须使用json对象作为参数可以这样:

// 生成参数

const params = {

"id":user.userName,

"password": "6****8",

};

// 生成header

const header = {

"Content-Type": "application/json; charset=UTF-8"

};

// 发送请求

let data = await fetch("http://k***s.t***k.cn/l**b/device-control-v2/login-authentication/user/login",{

method: 'post',

headers:header,

// 这样的方式发送json对象

body:JSON.stringify(params)

}).then(async res=>JSON.parse(await res.text()));

并且还有注意:params最后一个对象后面也要有逗号,是判断json对象结束标志

推荐阅读

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: