$ npm i uni-http
// api.js
import { UniHttp } from 'uni-http';
class Api extends UniHttp {
config = {
baseURL: 'https://jsonplaceholder.typicode.com',
header: {
'Content-Type': 'application/json'
}
};
// 你可以在这里制作一个简易的拦截器
request(...args) {
console.log(args);
return super.request(...args).then(res => res.data);
}
async hello() {
return this.get("/todos/1");
}
}
const api = new Api();
export { api };
import { api } from "api.js"
api.hello().then(data => { console.log(data); });
import { UniHttp } from 'uni-http';
const api = new UniHttp({
baseURL: 'http://localhost:3000'
});
const res = await api.get('/api/hello', {
params: { name: 'ajanuw' },
header: { 'x-id': 1 }
});
// or
const res = await api.get({
url: '/api/hello',
params: { name: 'ajanuw' },
header: { 'x-id': 1 }
});
import { UniHttp } from 'uni-http';
const api = new UniHttp({
baseURL: 'http://localhost:3000',
header: {
'Content-Type': 'application/json'
},
});
await api.post('/api/login', {
data: {
name: 'ajanuw'
}
});
class MyInterceptors {
request(options) {
options.header['x-token'] = 'xxxyyy';
uni.showLoading();
}
complete(result, options) {
uni.hideLoading();
}
}
const api = new UniHttp({
baseURL: 'http://localhost:3000',
interceptors: [new MyInterceptors()]
});
type OrPromise<T> = T | Promise<T>;
type C = IUniHttpConfig;
type RSCR = UniApp.RequestSuccessCallbackResult;
type GCR = UniApp.GeneralCallbackResult;
export interface UniHttpInterceptors {
/**
* 发送前拦截
*/
request?: (options: C) => void;
/**
* 在success拦截
*/
success?: (result: RSCR, options: C) => OrPromise<RSCR>;
/**
* 在fail拦截
*/
fail?: (result: GCR, options: C) => void;
/**
* 在complete拦截
*/
complete?: (result: GCR, options: C) => void;
}
uni.chooseImage({
success: async chooseImageRes => {
const tempFilePaths = chooseImageRes.tempFilePaths;
const r = await api.post('/api/upload', {
name: 'file',
filePath: tempFilePaths[0],
data: {
name: 'ajanuw'
}
});
}
});
class MyInterceptors {
request(options) {
// #ifdef H5
if(process.env.NODE_ENV === 'development') options.baseURL = '';
// #endif
}
}
const api = new UniHttp({
baseURL: 'http://xxx.fun/',
interceptors: [new MyInterceptors()]
});
manifest.json:
"h5": {
"devServer": {
"https": false,
"proxy": {
"/api": {
"target": "http://xxx.fun/",
"changeOrigin": true,
"secure": false
}
}
}
}
import { UniHttp, UniHttpInterceptors, UniAbortController } from 'uni-http';
class MyInterceptors {
fail(result) {
if (result.errMsg === 'request:fail abort') {
console.log('请求被中断')
}
return result;
}
}
const api = new UniHttp({
baseURL: 'http://xxx.fun/',
interceptors: [new MyInterceptors()]
});
const abortController = new UniAbortController();
api.get('/api/cats', {
abortController: abortController,
}).then(console.log)
// 中断请求
abortController.abort();
class MyInterceptors {
request(options) {
// 将cancel设置为true,请求将不会发送
// 并且会调用拦截器的fail和complete
options.cancel = true;
}
fail(result) {
// { errMsg: "request:fail cancel" }
}
}
这通常在h5上很有用
const api = new UniHttp({
baseURL: 'https://jsonplaceholder.typicode.com',
// #ifdef H5
async requestFunc(url, options, success, fail, complete) {
// console.log(url,options,success,fail,complete);
try {
const res = await fetch(url)
const d = await res.json();
success(d);
complete(d);
} catch (e) {
fail(e)
}
},
// #endif
});
await api.get('/todos/1').then(res => {
console.log(res);
});