代码拉取完成,页面将自动刷新
基于 axios 封装的微信小程序请求工具,完全使用Promise,并提供了请求和响应的拦截器。
import axios from './libs/mini-axios.min.js'
// http.js
import axios from './libs/mini-axios.min.js'
axios.get(url).then(res => {
console.log(res )
})
// 或者
axios.defaults.baseURL = 'https://xxx.com/' // 配置默认地址
axios.get(url).then(res => {
console.log(res)
})
==默认已经绑定App,Page,Component 与导入的axios是同一个实例==
//只需要在app.js中导入就好
--app.js
import axios from './libs/mini-axios.min.js'
App({
onLaunch: function () {
this.$axios.get(url).then(res => {
console.log(res)
})
}
})
--pages/index/index.js
//不需要再导入了 直接使用
Page({
onLoad:function(){
this.$axios.post(url).then(res => {
console.log(res)
})
}
})
let data = {
userId: 1,
username:"张三"
};
axios.get(url, data).then(res=> {
console.log(res)
})
function getUserInfo(){
return axios.get(url)
}
function getList(){
return axios.get(url)
}
axios.all([getUserInfo, getList]).then(res=> {
console.log(res)
}).catch(error => {
console.log(error)
})
axios.race([getUserInfo, getList]).then(res=> {
console.log(res)
}).catch(error => {
console.log(error)
})
axios(config)
axios({
method: 'POST',
url: url,
data: {
userId:1
}
}).then(res=> {
console.log(res)
}).catch(err => {
console.log(err)
})
// 或
axios.defaults.baseURL = 'https://xxx.com'
axios({
method: 'POST',
url: url,
data: {
userId:1
}
}).then(res=> {
console.log(res)
})
axios.(url[,config])
axios(url, {
method: 'POST',
data: {
userId:1
}
}).then(res=> {
console.log(res)
})
小程序中定义了8种请求类型:微信小程序请求方式
let server1 = axios.create({
baseURL: 'https://xxx.com'
})
let server2 = axios.create({
baseURL: 'https://xxx.com'
})
server1.get(url).then(res => {
console.log(res)
})
部分配置参数和微信小程序的配置一样 微信小程序 request 请求参数列表
参数 | 说明 | 类型 | 默认值 |
---|---|---|---|
baseURL | 默认地址 baseURL 将自动加在 url 前面 |
string |
'' |
url |
url 是用于请求的服务器 URL |
string |
'' |
data |
data 是作为请求主体被发送的数据 |
object |
{} |
header |
headers 是即将被发送的自定义请求头 |
object |
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' |
method |
method 是创建请求时使用的方法 |
string |
'GET' |
dataType |
dataType 是返回的数据类型 |
string |
'json' |
responseType |
responseType 是响应的数据类型 |
string |
'text' |
axios.defaults.baseURL = 'https://xxx.com'
mini-axios 也提供了和 axios 一样的请求拦截和响应拦截,并且可以配置多个
// 1.第一个 request 的拦截器
axios.interceptors.request.use(config => {
config.data.companyId = 1
// ...do something
return config
})
// 2.第二个 request 的拦截器,
axios.interceptors.request.use(config => {
config.data.token = wx.getStorageSync('token')
// ...do something
return config
})
// 1.第一个 response 的拦截器
axios.interceptors.response.use(response => {
if (response.statusCode === 200) {
// ...do something
}
console.log(response.header);
return response
})
// 2.第二个 response 的拦截器,
axios.interceptors.response.use(function (response) {
if (response.status === 400) {
// ...do something
}
return response
})
MIT
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。