ponjs / uni-ajax Goto Github PK
View Code? Open in Web Editor NEWLightweight HTTP client for the uni-app
Home Page: http://uniajax.ponjs.com
License: MIT License
Lightweight HTTP client for the uni-app
Home Page: http://uniajax.ponjs.com
License: MIT License
// 添加请求拦截器
request.interceptors.request.use(config => {
try {
uni.showNavigationBarLoading()
const token = uni.getStorageSync('token');
if (token) {
// 判断是否存在token,如果存在的话,则每个http header都加上token
config.headers.Authorization = token;
}
config.headers.type = "user"; // type:user 是固定的
console.log(config.headers)
return config;
} catch (e) {
uni.hideNavigationBarLoading()
uni.showToast({
title: '发生错误,请稍后重试',
position: 'center',
icon: 'none',
duration: 2000
})
}
},
err => {
uni.hideNavigationBarLoading()
return Promise.reject(err);
}
);
fulfilled
里面抛出错误或者普通拦截器返回 Promise.reject()
,相关错误会被移交到后一步的拦截器的rejected
里面处理。目前仅发现问题所在,暂时没想到解决办法。request.js
import ajax from 'uni-ajax'
import httpConfig from '../config/http.js'
const instance = ajax.create({ baseURL: httpConfig.baseURL })
// 请求拦截
instance.interceptors.request.use(
function (config) {
config['header']['Authorization'] = uni.getStorageSync('token')
return config
},
function (error) {
return Promise.reject(error)
}
)
// 响应拦截
instance.interceptors.response.use(
function (response) {
if (response.data && response.data.code === 401 && response.config.url !== '/logout') {
console.log('会话超时,请重新登录')
}
return response.data
},
function (error) {
return Promise.reject(error)
}
)
class HTTP {
// POST请求
post(url, data) {
let config = JSON.parse(JSON.stringify(httpConfig))
return instance.post(url, JSON.stringify(data), config)
}
}
export default HTTP
config/http.js
export default {
// 默认请求方式
method: 'POST',
// 基础url前缀
baseURL: 'xxx',
// 请求头信息
header: {
'Content-Type': 'application/json;charset=UTF-8'
},
// POST参数
data: { test: 123 },
// GET参数
params: {},
// 超时时间
timeout: 15000,
// 携带凭证
withCredentials: false,
// 返回数据类型
responseType: 'json'
}
`
api/common.js
`
import HTTP from '../http/request.js'
// 登录
function login(reqdata) {
return new HTTP().post('/member/login', reqdata)
}
export default {
login
}
页面
login() {
this.logining = true
api
.login(this.form)
.then(res => {
console.log(res)
if (res.code === 200) {
uni.setStorageSync('token', res.data.Authorization)
uni.setStorageSync('userinfo', res.data.member)
this.$utils.toast.success('登录成功')
this.$utils.router.switchTab('/pages/index/index')
} else {
this.$utils.toast.info(res.msg || '登录失败,请稍后重试')
}
this.logining = false
})
.catch(err => {
console.log(err)
this.logining = false
this.$utils.toast.info('网络异常,请稍后重试')
})
}
问题描述:
微信小程序接口200了,但是在request.js里的响应拦截里也打印不出日志,在方法里也打印不出,没进任何一个回调,包括finally。不知道啥原因
Version 2.5.1
nvue文件,在 mounted 时请求接口发现没有任何数据,抓包后发现没有任何请求。
export interface AjaxInstance<T extends AjaxConfigType> extends AjaxInvoke {
get: AjaxInvoke
post: AjaxInvoke
put: AjaxInvoke
delete: AjaxInvoke
connect: AjaxInvoke
head: AjaxInvoke
options: AjaxInvoke
trace: AjaxInvoke
getURL(config?: AjaxConfigType): Promise<string>
readonly defaults: AjaxRequestConfig
readonly config: T
interceptors: {
request: AjaxInterceptorManager<AjaxRequestConfig>
response: AjaxInterceptorManager<AjaxResponse>
}
}
场景是想要处理全局loading,在各个请求时加额外参数控制当前请求是否loading.
instance.interceptors.response.use(
(response: AjaxResponse<HttpResponse>) => {
const res = response.data;
if (res.code !== 200) {
uni.showToast({
title: res.msg || "Error",
icon: "none",
duration: 5 * 1000,
});
if ([400, 401, 403].includes(res.code)) {
uni.navigateTo({
url: "/pages/login/index",
});
}
return Promise.reject(new Error(res.msg || "Error"));
}
return res;
},
(error) => {
uni.showToast({
title: error.msg || "Request Error",
icon: "none",
duration: 5 * 1000,
});
return Promise.reject(error);
}
);
interface HttpResponse<T = unknown> {
code: number;
msg: string;
data: T;
}
怎么发起文件上传请求啊,有demo示例吗
如题。
"uni-ajax": "^2.5.1",
instance.interceptors.request.use(
config => {
config.header['Content-Type'] = 'application/json;charset=UTF-8'
if (HttpBridge.onBeforeRequest) {
HttpBridge.onBeforeRequest(config)
}
return config
},
error => {
// 提供外部处理
if (HttpBridge.onRequestError) {
HttpBridge.onRequestError(error)
}
return Promise.reject(error)
},
)
instance.interceptors.response.use(
response => {
// 提供外部处理
if (HttpBridge.onAfterResponse) {
HttpBridge.onAfterResponse(response)
}
return response.data
},
error => {
if (HttpBridge.onResponseError) {
HttpBridge.onResponseError(error)
}
return Promise.reject(error)
}
)
request能响应
vue3+vite cli创建的项目
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.