数据类型

方法 内容类型(Content-Type) 编码方式
GET \ Query String Parameters
POST application/json Request Payload
POST application/x-www-form-urlencoded Form Data
POST multipart/form-data Form Data

        

  • Content-Type,用于定义网络文件的类型和网页的编码,决定文件接收方将以什么形式、什么编码读取这个文件。

    • application/json:参数的类型是JSON,后端一般用实体类对象或者具体的参数接收,还可以使用集合接收。
    • application/x-www-form-urlencoded:参数的类型是被编码过的表单数据,后端一般用实体类对象或者具体的参数接收,还可以从Paramer中获取。
    • multipart/form-data:参数的类型是表单数据,后端一般用实体类对象或者具体的参数接收,还可以从Paramer中获取。
  • 编码方式

    • Query String Parameters:参数的传递方式为拼接在网址上,格式为加使用&连接的参数,空格则用+表示。
    • Request Payload:参数的传递方式是在放在Payload Body即请求体中,格式为:key:value
    • Form Data:参数的传递方式是放在表单中,格式为name:value

 GET方法请求的参数默认是直接拼接在url后面的,Content-Type是无法进行修改的。

POST方法Content-Type的修改方式:

  • 指定全局默认请求头: axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
  • 直接在请求中指定: {headers:{'Content-Type':'application/x-www-form-urlencoded'}}

前端发送

axios官方文档

GET

GET请求的Content-Type默认为:application/json

axios.get('/user?id=999&name=ahzoo')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });


// 上面的请求也可以这样做
axios.get('/user', {
    params: {
        id: 999,
        name: 'ahzoo',
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

图片
图片

POST

application/json

      axios
        .post('/api/ahzoo', {
          id: 999,
          name: 'ahzoo',
        })
        .then(function (response) {
          console.log(response);
        })
        .catch(function (error) {
          console.log(error);
        });

图片
可以看到数据在payload(负载)中,且数据格式为JSON:
图片

multipart/form-data

      let formData = new FormData();
      formData.append('id', 999);
      formData.append('name', 'ahzoo);
      axios
        .post('/api/ahzoo', formData)
        .then(function (response) {
          console.log(response);
        })
        .catch(function (error) {
          console.log(error);
        });

图片
图片

application/x-www-form-urlencoded

方式一:

      let param = new URLSearchParams();
      param.append('id', 999);
      param.append('name', 'ahzoo');
      axios
        .post('/api/ahzoo', param)
        .then(function (response) {
          console.log(response);
        })
        .catch(function (error) {
          console.log(error);
        });

图片
图片

方式二:
使用QS,官方地址(axios自带qs库,无需再次安装)

qs是查询字符串解析和将对象序列化的库,qs的两个主要使用方法:

  • qs.stringify():将对象序列化成url的形式,以&进行拼接
  • qs.parse():将url解析成对象形式
      axios
        .post(
          '/api/ahzoo',
          qs.stringify({
            id: 999,
            name: 'ahzoo'
          })
        )
        .then(function (response) {
          console.log(response);
        })
        .catch(function (error) {
          console.log(error);

        });

图片
图片

对象嵌套

使用默认的方式传递数据时,如果参数为对象,是需要将对象序列化操作的:

      let user = {
        username: '十玖八柒',
        url: 'ahzoo.cn',

      };
      let param = new URLSearchParams();
      param.append('id', 999);
      param.append('name', 'ahzoo');
      param.append('user', JSON.stringify(user));
      axios
        .post('/api/ahzoo', param)
        .then(function (response) {
          console.log(response);
        })
        .catch(function (error) {
          console.log(error);
        });

后端接收到的也是序列化后的对象,也就是json数据:
图片
而使用QS序列化的话,是不用再将参数中的对象序列化的:

      axios
        .post(
          '/api/ahzoo',
          qs.stringify({
            id: 999,
            name: 'ahzoo',
            user: user
          })
        )
        .then(function (response) {
          console.log(response);
        })
        .catch(function (error) {
          console.log(error);
        });

后端可以直接从Paramer中通过获得参数名为对象[属性]的方式(示例:get("user[url]"))获取数据

图片

并发请求

执行多个并发请求:

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // 两个请求现在都执行完成
  }));

默认配置

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

拦截器

在请求或响应被 thencatch 处理前拦截它们。

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });

移除拦截器:

const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

说明

关于一些自定义操作,请移步官方文档

后端接收

Query String Parameters和Form Data

Query String ParametersForm Data在后端的接收方式一样

方式一:
Request中拿到对应的Parameter数据

import javax.servlet.http.HttpServletRequest;

......

@RequestMapping("api/ahzoo")  
public void toGetInfo(HttpServletRequest request){  
    String id = request.getParameter("id");  
    String name = request.getParameter("name");  
    System.out.println(id); // 999
    System.out.println(name); // ahzoo
}

图片
方式二:
直接使用对应的参数名或者实体类拿到Request中的数据:

@RequestMapping("api/ahzoo")  
public void toGetInfo(String name, String id){  

    System.out.println(id); // 999  
    System.out.println(name); // ahzoo
}

图片

@RequestMapping("api/ahzoo")  
public void toGetInfo(Info info){  

    System.out.println(info); // Info(id=999, name=ahzoo)
}

图片

Request Payload

因为参数是直接放在请求体(Payload Body)中,所以需要从请求体中拿到数据:
使用@RequestBody注解从请求体中拿到数据,同样也是可以使用对应的实体类或参数接收

import org.springframework.web.bind.annotation.RequestBody;

......
@RequestMapping("api/ahzoo")
public void toGetInfo(@RequestBody Info info){  
    System.out.println(info); // Info(id=999, name=ahzoo)
}

图片

    @RequestMapping("api/ahzoo")  
    public void toGetInfo(@RequestBody String id, @RequestBody String name){   
        System.out.println(name); // ahzoo  
        System.out.println(id); // 999
    }

图片
由于参数是JSON格式的,所以还可以使用集合接收:

@RequestMapping("api/ahzoo")  
public void toGetInfo(@RequestBody HashMap<String,String> info){  

    String id = info.get("id");  
    String name = info.get("name");  

    System.out.println(id); // 999  
    System.out.println(name); // ahzoo
}

图片

对象嵌套

接收序列化的对象:
和接收普通的参数一样,用字符串类型数据接收,或者直接从Paramer中获取

@RequestMapping("api/ahzoo")  
public void toGetInfo(String id, String name, HttpServletRequest request) {  

    String user= request.getParameter("user");  // {"username":"十玖八柒","url":"ahzoo.cn"}
    System.out.println(name);  // ahzoo 
    System.out.println(id); // 999
}

图片

接收QS传递的对象:

@RequestMapping("api/ahzoo")  
public void toGetInfo(String id, String name, HttpServletRequest request) {  

    String username = request.getParameter("user[username]");  // 十玖八柒
    String url = request.getParameter("user[url]");  //ahzoo.cn
    System.out.println(name); // ahzoo
    System.out.println(id); // 999
}

图片

知识积累
将Maven项目组件上传到Maven中心仓(借助sonatype)
2024/7/21
String.valueOf()踩坑记录
2024/7/21
使用Mapstruct轻松实现实体类转换
2024/7/21
前端知识积累
浏览器注入外部JS文件
2024/7/21
Vue(JavaScript)下载文件方式汇总
2024/7/21
Axios携带数据发送请求及后端接收方式
2024/7/21
发表评论