Wx. Request packaging
- Define config configuration options
// create config.js const config = {baseUrl:'http://www.baidu.com/api', // Example appKey:'xxxx',}export default config;
Copy the code
The export and export default
- Export You can export multiple modules
- Export Default can export only a single module
- Create an HTTP class to encapsulate the request
// create util/http.js // import config from config'.. /config'; // Define error code const err_tip = {1:'An error has occurred',
10001: 'xxxx',
10002: 'xxxx'
}
class HttpRequest{
request(params){
wx.request({
url: config.url + params.url,
method: params.method || 'GET',
data: params.data,
header: {
'content-type': 'application/json',
appKey: config.appKey, //
},
success: (res) => {
let code = res.statusCode;
if(code.startsWith('2'){// Call params.success(res.data)}else{this._show_errmsg (res.data.error_code) console.log() {this._show_errmsg (res.data.error_code) console.log('err',res.data)
}
},
fail: (err) => {
this._show_errMsg(1)
}
})
}
_show_errMsg(err_code){
if(! err_code){ wx.showToast({ title: err_tip[1], icon:'none',
duration: 1500
})
}
wx.showToast({
title: err_tip[err_code],
icon: 'none',
duration: 1500
})
}
}
export default HttpRequest;
Copy the code
- Use in pages
import HttpRequest from '.. /.. /util/http.js';
let http = new HttpRequest()
onLoad: function(){
http.request({
url: '/xxx/xx',
method: 'POST', / /'GET'Data: {XXX,yyy}, success: (res) => {console.log(res.data)}})}Copy the code
Thanks for teacher 7yue’s lessons