uniapp使用luch-request

官网:https://www.quanzhan.co/luch-request/

  1. 下载luch-request插件,将插件放在common目录里
  2. 在根目录下的common目录里创建http目录,新建index.js
  3. commom/http/index.js
import Request from '@/common/luch-request/index.js'
const http = new Request();
import {baseUrl} from './baseUrl.js'
 
let defaultUrl = ''
if(process.env.NODE_ENV === 'production'){
	defaultUrl = baseUrl
}else{
	defaultUrl = 'xxxx'
}
 
http.setConfig((config) => { /* 设置全局配置 */
	config.baseURL = defaultUrl
	config.custom = {
		loading:true
	} 
	config.header = {
		
		// a: 1, // 演示用
		// b: 2 // 演示用
	}
	return config
})
 
//请求前拦截,用来动态加参
http.interceptors.request.use((config) => { // 可使用async await 做异步操作
	if(config.url !== '/logins' && config.url!=='/captcha/logins'){
		config.header.Authorization ='Bearer '+ uni.getStorageSync("token")
	}
	
	console.log('请求前拦截header',config)
	if(config.url == '/images'){
		config.header = {
        'Accept': 'application/json',
        'Content-Type': 'multipart/form-data',
		'Authorization':'Bearer' +' ' + uni.getStorageSync("token")
      }
	}
	config.header = {
		...config.header,
		a: 1 // 演示拦截器header加参  
	}
	// 演示custom 用处  
	if (config.custom.loading) {
		uni.showLoading()
	}
	return config
}, (config) => {
	return Promise.reject(config)
})
 
 
// 请求后
http.interceptors.response.use((response) => {
	
	if (response.config.custom.loading) {
		uni.hideLoading()
	}
	if (response.statusCode > 300 ||response.statusCode< 200) { 
		console.log('reject')
	  return Promise.reject(response)  
	} 
	return response.data
}, (response) => { // 请求错误。可以使用async await 做异步操作  
	console.log(response,'错误')
	if (response.config.custom.loading) {
		uni.hideLoading()
	}
	if(response.statusCode == 401){
		uni.clearStorageSync();
		uni.showToast({
		    title: '登录失败,请重新登录',
		    duration: 2000
		});
		
		if(response.config.url !== "/logins"){
			uni.reLaunch({
				url:'/pages/login/login'
			})
		}
	}else{
		uni.showToast({
		    title: response.data.messages[0].content,
			icon: 'none',
		    duration: 2000
		});
	}
	return Promise.reject(response)
})
export default http

4、在main.js里引入

import * as http from './common/http/index.js'
 
Vue.prototype.$http = http;

5、在页面里调用

this.$http.get(`/i/list`).then(res => {
	this.data = res
}).catch(err => {})
this.$http.post('/logins', {
	mobile: this.form.mobile
}).then(res => {
	....				
}).catch(err => {})

baseUrl.js 里 为 export let baseUrl = ‘http://192.168.1.1’,也可以直接写在这个页面

转载:https://blog.csdn.net/lll_liuhui/article/details/109055111

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值