首页 > 建站教程 > 前端框架 >  element axios 发送Form Data数据正文

element axios 发送Form Data数据

element基于axios封装的request默认发送的是application/json,如果要发送form-data,需要做以下修改

一、在request.js将“application/json;charset=UTF-8”改成“application/x-www-form-urlencoded”
1const service = axios.create({
2  headers: { 'Content-Type': 'application/json;charset=UTF-8' }
3})
但是这样改,所有的请求都会变成formdata,如果只想改某些接口,可以在接口api加个标识,如下:
1export function findCameraPage(data) {
2  return request({
3    url: `/pms/hikvision/findCameraPage`,
4    method: 'post',
5    isForm: true,
6    data
7  })
8}
二、然后在请求拦截里面,做个判断:
01service.interceptors.request.use(
02  config => {
03    if (config.isForm){
04      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
05    }
06    return config
07  },
08  error => {
09    // do something with request error
10    console.log(error) // for debug
11    return Promise.reject(error)
12  }
13)
三、发送数据也要改成formData:
01getVideoList(){
02      let formData = new FormData();
03      //参数
04      formData.append("page",1);
05      formData.append("size",10);
06      findCameraPage(formData).then(response => {
07          //请求成功
08        if (response.code === 0) {
09           
10        }
11      }).catch(res => {
12          //请求失败
13      })
14},
上面用传统的new FormData比较麻烦,可以安装qs
1import qs from 'qs'
然后更改第二步,将data直接批量改为formData格式:
01service.interceptors.request.use(
02  config => {
03    if (config.isForm){
04      config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
05      config.data = qs.stringify(config.data) // 转为formdata数据格式
06    }
07    return config
08  },
09  error => {
10    // do something with request error
11    console.log(error) // for debug
12    return Promise.reject(error)
13  }
14)
将第三步的formData省略,还是按照常规传参即可:
01getVideoList(){
02      findCameraPage({
03          page: 1,
04          size: 10
05      }).then(response => {
06          //请求成功
07        if (response.code === 0) {
08           
09        }
10      }).catch(res => {
11          //请求失败
12      })
13},