common.ts
export default class CommonConstant {
static readonly SERVER: string = '请求接口地址';
static readonly SUCCESS_CODE: number = 200;
static readonly READ_TIMEOUT: number = 50000;
static readonly CONNECT_TIMEOUT: number = 50000;
}
request.ts
import http from '@ohos.net.http';
import CommonConstant from './common';
import Prompt from '@system.prompt';
const request = (url: string, data?: Object, header?: Object,) => {
return new Promise((resolve, reject) => {
let h
if (header) {
h = header
} else {
h = {
'Content-Type': 'application/json',
}
}
let httpRequest = http.createHttp();
httpRequest.on('headersReceive', (header) => {
});
httpRequest.request(
CommonConstant.SERVER + url,
{
method: http.RequestMethod.POST,
header: h,
extraData: data,
expectDataType: http.HttpDataType.STRING,
usingCache: true,
priority: 1,
connectTimeout: 60000,
readTimeout: 60000,
}, (err, res: any) => {
if (!err) {
console.info('Result:' + res.result);
resolve(JSON.parse(res.result))
} else {
console.info('error:' + JSON.stringify(err));
Prompt.showToast({
message: JSON.stringify(err)
})
return JSON.stringify(err)
httpRequest.off('headersReceive');
httpRequest.destroy();
}
});
})
}
export default request
接口汇总
import request from "./request"
const loginApi = {
async login(data: object) {
return await request('/account/login', data, {Token: false})
}
}
export default loginApi
页面调用
import loginApi from "../../api/login"
loginApi.login({
account: this.account,
password: this.password
}).then((res: any) => {
if (res.code == 1) {
console.info(res.data)
}
})