网络请求小程序提供了wx.request
// 官方例子
wx.request({
url: 'test.php', //仅为示例,并非真实的接口地址
data: {
x: '' ,
y: ''
},
header: {
'content-type': 'application/json' // 默认值
},
success: function(res) {
console.log(res.data)
}
})
小程序支持ES6,那么就应该支持Promise 了,下面是我封装的请求
Promise封装
const baseUrl = 'https://csdn.net';
export const http = ({ url = '', param = {}, method="get",...other } = {}) => {
wx.showLoading({
title: '请求中,请耐心等待..'
});
let timeStart = Date.now();
return new Promise((resolve, reject) => {
wx.request({
url: getUrl(url),
data: param,
methods,
header: {
'content-type': 'application/json' // 默认值 ,另一种是 "content-type": "application/x-www-form-urlencoded"
},
...other,
complete: (res) => {
wx.hideLoading();
console.log(`耗时${Date.now() - timeStart}`);
if (res.statusCode >= 200 && res.statusCode < 300) {
resolve(res.data)
} else {
reject(res)
}
}
})
})
}
我这方便以后好维护 创建了一个api文件夹 每个页面每个模块再api下面创建一个文件夹
比如:
在我们创建好的index.js下面 引入我们封装好的http.js
import http from '@/utils/http.js'
export function editApi(query) {
return http({
url: '/iwopbase/fenceinfo',
method: 'put',
param : query
})
}
如果要在页面上用 我们就可以引入对应的接口
import {editApi} form "@/api/ccc/index.js";
let params = {
id:321,
}
editApi(params).then(res=>{
})
留下你的赞吧