1.创建api公共文件公共文件夹
创建文件 request.ts
import { baseUrl } from '../utils/config'
type config = {
url: string,
data: object,
header: object,
method: "GET" | "POST"|"DELETE"|"PUT"|"OPTION"
}
const http = {
request: (config: any) => {
config.header = config.header || {
'content-type': 'application/json'
}
config.method = config.method||'GET'
config.url = config.url.startsWith('http') ? config.url : baseUrl + config.url
return new Promise((resolve, reject) => {
wx.request({
url: config.url,
data: config.data,
method: config.method,
header: config.header,
success(res) {
resolve(res.data)
},
fail(err) {
reject(err)
}
})
})
},
post(url:any,config:any){
return http.request({
...config,
method:"POST",
url
})
},
get(url:any,config:any){
return http.request({
...config,
method:"GET",
url
})
},
}
export default http
2.在utils创建config文件,里面填写主地址
创建 config.ts
export const baseUrl = "https://b21215267-48b7-aefb-016e5c1d7445.bspapp.com/http"
3.在分开创建每个界面所用的接口,自己搭配即可
例如:创建home主界面接口
创建home.ts接口文件
import request from './request' // 引入request.ts封装的接口
export const getBanner = () =>request.get('/house/get_banner') // 接口1
export const getList = (params:any) =>request.post('/house/get_house_list',params) // 接口2
4.使用封装的api,类似axios
getBanner().then((res:any)=>{
this.setData({
imgs: res.data
})
})
文件夹位置参考,可根据自己所需求创建文件,仅供参考