configConstant.js
const BASE_URL_LOCAL = "http://192.168.5.17";//本地环境
const BASE_URL_DEVELOPMENT = "https://qa.qugaiba.com"; //测试(以实际开发api文档为准)
const BASE_URL_PRODUCTION = "https://qugaiba.com"; //正式服(以实际开发api文档为准)
const LOGINAPI = "/qugai/api2/v1/login/wechat"; //登录接口(以实际开发api文档为准)
const FORMIDAPI = "/qa/api/v1/"; //用于存放用户formId接口(以实际开发api文档为准)
const BASE_URL = {
local: `${BASE_URL_LOCAL}${FORMIDAPI}`,
development: `${BASE_URL_DEVELOPMENT}${FORMIDAPI}`,
production: `${BASE_URL_PRODUCTION}${FORMIDAPI}`,
};
const ENV = "local";//本地环境
// const ENV = "development";//测试环境
// const ENV = "production";//正式环境
export{
BASE_URL,
ENV,
LOGINAPI,
FORMIDAPI
};
http.js
import {BASE_URL,ENV} from "./constant/configConstant.js";
class rp {
constructor(url, type) {
this.url = `${BASE_URL[ENV]}${url}`;
this.method = type;
this.headers = {};
this.qs = {};
this.body = {};
}
header(v1, v2) {
if (typeof v1 === 'object') {
this.headers = v1;
} else {
this.headers[v1] = v2;
}
return this;
}
query(v1, v2) {
if (typeof v1 === 'object') {
this.qs = v1;
} else {
this.qs[v1] = v2;
}
return this;
}
send(data) {
this.body = data;
return this;
}
async end() {
let auth = wx.getStorageSync('token');
if (auth) {
this.header('Authorization', auth);
}
let rpOpt = {
url: this.url,
header: this.headers,
method: this.method,
data: this.body
};
let isJsonType = this.method === 'POST' || this.method === 'PUT';
let qs = [];
for (let k in this.qs) {
qs.push(`${k}=${this.qs[k]}`);
}
if (qs.length !== 0) {
qs = qs.join('&');
rpOpt.url += rpOpt.url.indexOf('?') === -1 ? `?${qs}` : `&${qs}`;
}
if (isJsonType) {
rpOpt.data = this.body;
rpOpt.dataType = 'json';
if(!this.headers){
rpOpt.header['Content-Type'] = 'application/json';
}
}
let [err,res] = await uni.request(rpOpt);
console.log(res.header.authorization)
if(res.header?.authorization && res.header?.authorization !== auth){
uni.setStorageSync("token",res.header.authorization);
}
let info = res.data;
if(info.code === 1){
return info;
}
if(info.message && !info.message){
info.moreInfo = info.message;
}
return info
}
}
const shttp = {
get: (url) => {
return new rp(url, 'GET');
},
post: (url) => {
return new rp(url, 'POST');
},
put: (url) => {
return new rp(url, 'PUT');
},
delete: (url) => {
return new rp(url, 'DELETE');
},
};
export{
shttp,
rp
};
用法示例
-
在 script 中引入
import { shttp } from "../utils/http";
get 请求例子
async gettest() { const res = await shttp .get(`apiUrl`) .query({key1:'value'}) .end(); }
put 请求例子
async puttest() { const res = await shttp .put(`apiUrl`) .send({key1:'value'}) .end(); }
post 请求例子
async posttest() { const res = await shttp .post(`apiUrl`) .send({key1:'value'}) .end(); }
delete 请求例子
async deletetest() { const res = await shttp .delete(`apiUrl`) .query({id:id}) .end(); }