可以在 axios 的请求拦截器中获取请求头的 Content-Type 属性,然后根据不同的数据类型使用不同的序列化方式。具体实现步骤如下:

  1. 安装 qs 库,命令为 npm install qs

  2. 引入 qs 库和 axios 库

import qs from 'qs';
import axios from 'axios';
  1. 在 axios 的请求拦截器中获取请求头的 Content-Type 属性
axios.interceptors.request.use(
  config => {
    // 获取请求头的 Content-Type 属性
    const contentType = config.headers['Content-Type'];
    // 判断是否为 application/x-www-form-urlencoded 类型
    if (contentType === 'application/x-www-form-urlencoded') {
      // 使用 qs 库的 stringify 方法将参数序列化为字符串
      config.data = qs.stringify(config.data);
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);
  1. 根据不同的数据类型使用不同的序列化方式

在上面的代码中,我们根据请求头的 Content-Type 属性是否为 application/x-www-form-urlencoded 类型来使用 qs 库的 stringify 方法将参数序列化为字符串。如果请求头的 Content-Type 属性为 application/json 类型,则不需要使用 qs 库进行序列化处理,因为 axios 默认会将数据转换为 JSON 格式。

axios.interceptors.request.use(
  config => {
    // 获取请求头的 Content-Type 属性
    const contentType = config.headers['Content-Type'];
    // 判断是否为 application/x-www-form-urlencoded 类型
    if (contentType === 'application/x-www-form-urlencoded') {
      // 使用 qs 库的 stringify 方法将参数序列化为字符串
      config.data = qs.stringify(config.data);
    } else if (contentType === 'application/json') {
      // 不需要使用 qs 库进行序列化处理,axios 默认会将数据转换为 JSON 格式
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);
Axios 请求拦截器中使用 qs 根据 Content-Type 序列化数据

原文地址: https://www.cveoy.top/t/topic/mMcs 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录