在axios 封装类里判断是post请求的话给参数追加querystring.stringify()
时间: 2023-12-26 10:05:59 浏览: 47
当使用 `axios` 封装类时,可以在发送 `post` 请求时,为了防止参数被篡改,我们可以将参数序列化后再发送。可以使用 `querystring` 模块中的 `stringify()` 方法将参数序列化成字符串,然后在发送请求时将其作为请求体发送。
以下是一个示例代码,可以在 `axios` 封装类中判断请求方法是 `post` 时,将参数序列化后追加到请求体中:
```javascript
import axios from 'axios';
import queryString from 'querystring';
const instance = axios.create({
baseURL: 'https://api.example.com'
});
// 封装请求方法
class Http {
static async post(url, data) {
try {
let config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
if (data && typeof data === 'object') {
// 如果是对象,则序列化成字符串
data = queryString.stringify(data);
// 追加到请求体中
config.data = data;
}
const response = await instance.post(url, data, config);
return response.data;
} catch (error) {
throw error;
}
}
}
export default Http;
```
在上面的代码中,我们先判断 `data` 参数是否是对象,如果是,则使用 `querystring.stringify()` 方法将其序列化成字符串,然后将其作为请求体发送。如果不是对象,则直接将其发送。
需要注意的是,为了让服务器正确解析请求体中的参数,我们在 `headers` 中设置了 `Content-Type` 为 `application/x-www-form-urlencoded`,这表示请求体中的参数是使用 `application/x-www-form-urlencoded` 格式进行编码的。
相关推荐
![js](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)