// 快捷形式 wx.http.get/post/put/delete(url,data,headers)

// 通用形式 wx.http({ method,url,data,headers })

// 请求拦截器:

// wx.http.interceptors.request.use((config) => { return config })

// 响应拦截器:

// wx.http.interceptors.response.use((res) => { return res })

// 基准地址

// wx.http.baseURL = 'XXX'



function http(config) {

return new Promise((resolve, reject) => {

if (http.baseURL) {

if (config.url.startWith('/')) {

if (http.baseURL.endsWith('/')) {

config.url = http.baseURL.slice(0, 1) + config.url

} else {

config.url = http.baseURL + config.url

}

} else {

if (http.baseURL.endsWith('/')) {

config.url = http.baseURL + config.url

} else {

config.url = http.baseURL + '/' + config.url

}

}

}



config = http.interceptors.request._cb(config)



if (!config.method) {

config.method = 'GET'

}



if (config.headers) {

config.header = config.headers

delete config.headers

}



wx.request({

...config,

success(res) {

res = http.interceptors.response._cb(res)

resolve(res)

},

fail(err) {

err = http.interceptors.response._cb(err)

if (err instanceof Promise) {

resolve(err)

} else {

reject(err)

}

}

})

})

}



http.get = function (url, data, headers) {

return http({

method: 'GET',

url,

data,

headers

})

}



http.post = function (url, data, headers) {

return http({

method: 'POST',

url,

data,

headers

})

}



http.put = function (url, data, headers) {

return http({

method: 'PUT',

url,

data,

headers

})

}



http.delete = function (url, data, headers) {

return http({

method: 'DELETE',

url,

data,

headers

})

}



http.interceptors = {

request: {

_cb: config => config,

use(cb) {

this._cb = cb

}

},

response: {

_cb: res => res,

use(cb) {

this._cb = cb

}

}

}



http.baseURL = undefined



wx.http = http



export default http

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐