网络请求封装promise
(1)封装配置文件
global.js
const url = "http://localhost:3000";
export default url;
(2)封装网络请求promise
http.js文件
import url from "./global"
const http = (options={}) => {
return new Promise((resolve, reject) => {
wx.request({
url: url + options.url,
data:options.data || {},
header:options.header || {
"content-type": "application/json"
},
timeout: 30000,
method: options.method || "get",
success(res) {
resolve(res)
},
fail(err){
reject(err)
}
})
})
}
export default http;
(3)统一管理api接口
api.js文件
import http from "./http"
const _getProducts = (data={})=>{
var options = {
url:"/products",
data
}
return http(options);
}
const _doLogin = (data={})=>{
var options = {
url:"/login",
method:"post",
data,
}
return http(options)
}
export default {
_getProducts,_doLogin
}
(4)页面使用api
import api from "../../utils/api"
Page({
async _getInfo() {
let res = await api._getProducts({pass:123456});
console.log(res)
}
})