微信小程序--调用外部服务器接口

调用外部服务器接口

功能:

调用wx.request方法,访问https的API接口,返回数据。

首先,要在微信小程序后台,添加要访问的域名。

域名是有要求的,具体可以看看官网。

官方的介绍:https://developers.weixin.qq.com/miniprogram/dev/framework/ability/network.html

配置好域名后,就可以写调用代码了。

对应的.js文件

注意1:

配置完域名后,在开发者工具中刷新一下,确定其已经存在了。

微信小程序--调用外部服务器接口

注意2:

扫描二维码关注公众号,回复: 11179984 查看本文章

在访问的时候,添加一个header,否则无法返回数据。(参照着网上找到的答案,但是不明白为什么)

注意3:

要想在wx.request中,向data中添加数据,要先重新定义变量this

var that = this;

wx.request({
    url: 'https://www.rest-time.top/api/select_search',
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    data: {
      openid: uuid,
    },
    dataType: 'json',
    responseType: 'text',

    success: function(res) {
      // 不能直接用this.setData
      that.setData({
        arrived: res.data
      })
    }

})

感觉有用的小伙伴,点个赞再走撒~

猜你喜欢

转载自blog.51cto.com/feature09/2492408