微信小程序发起HTTP请求可以使用wx.request(Object object)
注意:在使用服务器接口地址时要先进行配置,否则将会出现如下错误
配置的注意事项为:
- 域名只支持
https
(wx.request、wx.uploadFile、wx.downloadFile) 和wss
(wx.connectSocket) 协议;- 域名不能使用 IP 地址(小程序的局域网 IP 除外)或 localhost;
- 可以配置端口,如 https://myserver.com:8080,但是配置后只能向 https://myserver.com:8080 发起请求。如果向 https://myserver.com、https://myserver.com:9091 等 URL 请求则会失败。
- 如果不配置端口。如 https://myserver.com,那么请求的 URL 中也不能包含端口,甚至是默认的 443 端口也不可以。如果向 https://myserver.com:443 请求则会失败。
- 域名必须经过 ICP 备案;
- 出于安全考虑,
api.weixin.qq.com
不能被配置为服务器域名,相关API也不能在小程序内调用。 开发者应将 AppSecret 保存到后台服务器中,通过服务器使用getAccessToken
接口获取access_token
,并调用相关 API;- 不支持配置父域名,使用子域名。
详情见官方文档:https://developers.weixin.qq.com/miniprogram/dev/framework/ability/network.html
若不进行配置,可在本地设置中开启不校验模式
基本的写法为
let _this=this
wx.request({
url: '',//服务器接口地址
method:'',//请求类型
data:{
name:_this.logtext,
password:_this.passtext
},
success:function(res){//接口调用成功的回调函数
wx.showToast({//弹框
title: '登录成功',
icon: 'success',
duration: 2000
})
},
fail:function(){//接口调用失败的回调函数
wx.showToast({
title: '登录失败',
icon: 'error',
duration: 2000
})
}
})
}