微信小程序如何实现请求拦截和响应拦截步骤
时间: 2024-06-08 18:11:53 浏览: 38
微信小程序可以通过使用拦截器对请求和响应进行拦截和处理。
下面是实现请求拦截和响应拦截的步骤:
1. 在 app.js 中定义一个拦截器
```javascript
App({
// 定义 request 拦截器
requestInterceptor: function (config) {
// 对 config 进行处理
config.header['Authorization'] = 'Bearer ' + wx.getStorageSync('token');
return config;
},
// 定义 response 拦截器
responseInterceptor: function (response) {
// 对 response 进行处理
if (response.statusCode === 401) {
wx.navigateTo({
url: '/pages/login/login'
});
}
return response;
}
});
```
2. 在 app.js 的 onLaunch 方法中注册拦截器
```javascript
App({
onLaunch: function () {
// 注册 request 拦截器
wx.request.interceptors.request.use(this.requestInterceptor);
// 注册 response 拦截器
wx.request.interceptors.response.use(this.responseInterceptor);
}
});
```
3. 发起请求时,请求会被拦截器拦截并进行处理
```javascript
wx.request({
url: 'https://example.com/api',
method: 'GET',
success: function (response) {
console.log(response.data);
},
fail: function (error) {
console.log(error);
}
});
```
在这个例子中,当发起请求时,请求会被 request 拦截器拦截并添加 Authorization 头部,然后被发送到服务器。当服务器返回响应时,响应会被 response 拦截器拦截并进行处理,如果响应码是 401,则跳转到登录页面。最后,响应会被返回给发起请求的代码。
相关推荐
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)