小程序实现请求接口数据

代码实现

1、新建文件请求接口域名

技术分享图片

 2、封装接口

  2-1、方法一:新建一个api.js

var _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(e) {
return typeof e;
} : function(e) {
return e && "function" == typeof Symbol && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e;
}, _rewx = require("./rewx.js"), app = getApp(),IndexData = function (i) {
return (0, _rewx.post)("/applet/index/index", i).then(function (o) {
return new Promise(function (e, n) {
e(o);
});
});
},
orderList= function (i) {
return (0, _rewx.post)("/applet/order/index", i).then(function (o) {
return new Promise(function (e, n) {
e(o);
});
});
}
module.exports={ IndexData:IndexData ,orderList:orderList
}

   目录文件调用

(0, _api.IndexData)().then(function (t) {
console.log(t)
that.setData({
})
});

   2-2、方法二:目录文件直接使用(get/post请求及带参数请求)

 (0, _rewx.post)("/applet/store/getdetail", { store_id: 1 }).then(function (t) {
console.log(t)
that.setData({
})
});
(0, _rewx.get)("/applet/index/index").then(function (t) {
console.log(t)
that.setData({
})
});

   2-3、方法三:直接请求

  wx.request({
url: ‘https://xxx.com/applet/store/getdetail‘,
data: {
x: ‘‘
},//get/post请求参数
method:"POST",
header: {
‘content-type‘: ‘application/json‘ // 默认值
      },
success: function(res) {
console.log(res.data)
}
})

具体代码已经放到了GitHub,有需要的小伙伴可以直接下载

https://github.com/sryhx/smallProduct

注意:请求之前需要在小程序后台-开发管理-开发设置-服务器域名配置

小程序实现请求接口数据

原文:https://www.cnblogs.com/rouyhx/p/15102709.html

以上是小程序实现请求接口数据的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>