2024-08-27 10:08:47 +08:00

110 lines
3.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 小程序中的网络请求
在小程序中,使用 wx.request( ) 这个方法来发送网路请求,整个请求的方式和 jQuery 里面的 $.ajax 方法是非常相似的。
在 wx.request( ) 这个方法中,接收一个配置对象,该配置对象中能够配置的项目如下表:
<img src="https://xiejie-typora.oss-cn-chengdu.aliyuncs.com/2023-01-12-020112.png" alt="image-20230112100111671" style="zoom: 50%;" />
## 关于服务器接口
有关服务器接口的配置,需要满足以下两点:
- 要求必须要是 https 接口
- https 接口对应的域名还必须要在小程序管理平台进行配置
【开发】-【开发管理】-【开发设置】下面有一个【服务器域名】,在这个位置进行配置
<img src="https://xiejie-typora.oss-cn-chengdu.aliyuncs.com/2023-01-12-020716.png" alt="image-20230112100715734" style="zoom:50%;" />
**我如果是开发环境怎么办?**
在开发环境下,因为开发阶段的服务器接口还没部署到现网的域名下,所以我们可以选择不校验 HTTPS 证书,具体的方式如下图所示:
<img src="https://xiejie-typora.oss-cn-chengdu.aliyuncs.com/2023-01-12-021116.png" alt="image-20230112101115812" style="zoom:50%;" />
## 向服务器传递参数
一般来讲,用得比较多的有 GET 和 POST 请求
- GET
- 可以放在 URL 后面URL 长度有限制,并且还会做一次 URL 的 encode
- 也可以放在 data 配置项目里面
- POST
- 只能放在 data 里面
综上所述,建议就把数据放在 data 里面
## 收到回包
只要收到了服务器返回的信息,都会进入到 success 的回调函数,然后我们再在 success 回调函数中根据服务器返回的内容来做下一步操作。
接下来,我们来看一个具体例子
到时候大家会拿到一个名为 server 的服务器代码,大家拿到后,首先使用 npm i 安装依赖包,安装完成后,使用 npm start 启动这个服务器即可。该服务器默认监听 3000 端口,该服务器提供两个接口:
- / :这是 GET 请求,服务器端会返回 {name : "zhangsan", age : 18}
- /abc这是一个 POST 请求,服务器端会返回 {name : "lisi", age : 20}
当你安装了依赖包,使用 npm start 启动服务器后,看到下面的画面说明服务器已经启动成功
<img src="https://xiejie-typora.oss-cn-chengdu.aliyuncs.com/2023-01-12-023354.png" alt="image-20230112103354180" style="zoom:50%;" />
接下来在小程序端通过 wx.request 进行请求的发送,代码片段如下:
```js
// 向服务器发送 Get 请求
sendGet(){
wx.request({
url: 'http://localhost:3000',
data : {
loginId : this.data.loginId,
password : this.data.password
},
success(e){
console.log(e);
}
})
},
// 向服务器发送 Post 请求
sendPost(){
wx.request({
url: 'http://localhost:3000/abc',
method : "POST",
data : {
loginId : this.data.loginId,
password : this.data.password
},
success(e){
console.log(e);
}
})
},
```
## 使用技巧
一般来讲,在发送请求的时候,有三点可以优化:
- 和服务器通信的过程中,需要显示一个 loading 框
- wx.showLoading( ):显示 loading 框
- wx.hideLoading( ):隐藏 loading 框
- 设置超时时间
- 在 app.json 中设置 networkTimeout
- 如果处理失败,需要显示一个提示
- wx.showToast( )
本节课结束之后,请通读官方文档对应的:*https://developers.weixin.qq.com/ebook?action=get_post_info&docid=000ee27c9c8d98ab0086788fa5b00a#_ftn3*