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