ruoyi-ui与后端交互
方法一:表单
使用 headers: {'Content-Type':'application/x-www-form-urlencoded'},
ruoyi-ui的vue中
//ruoyi-ui的vue中定义
formData: {a: '111',b: '111',c: 1,},
//vue中方法调用
outBound() { empty(this.formData).then(response => {})
},
ruoyi-ui的api中
//ruoyi-ui中js中api
export function empty(data) {const encodedData = qs.stringify(data);return request({url: '/A/info/empty',method: 'post',data: encodedData,headers: {'Content-Type':'application/x-www-form-urlencoded'},})
}
controller方法
//controller中方法
@RequestMapping("/A/info")
~~~@PreAuthorize("@ss.hasPermi('A:info:remove')")@PostMapping("/empty")public AjaxResult empty( String a, String b, Integer c) {return aInfoService.empty(a, b, c);}
方法二:json
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
ruoyi-ui的vue中
//ruoyi-ui的vue中定义
formData: {a: '111',b: '111',c: 1,},
//vue中方法调用
outBound() { empty(this.formData.a,this.formData.b,this.formData.c).then(response => {})
},
ruoyi-ui的api中
//ruoyi-ui中js中api
export function empty(a,b,c) {return request({url: '/A/info/empty/'+a+'/'+b+'/'+c,method: 'post',})
}
controller方法
//controller中方法
@RequestMapping("/A/info")@PostMapping("/empty/{a}/{b}/{c}")public AjaxResult empty( @PathVariable String a, @PathVariable String b, @PathVariable Integer c) {return aInfoService.empty(a, b, c);}
ruoyi-app与后端交互
方法一:表单
ruoyi-app的vue中
//ruoyi-app的vue中定义
formData: {a: '111',b: '111',c: 1,},
//vue中方法调用
outBound() { empty(this.formData).then(response => {})
},
ruoyi-app的api中
//ruoyi-app的js中api
export function empty(data) {return request({url: '/A/info/empty',method: 'post',data: data,header : {"Content-Type":"application/x-www-form-urlencoded"}})
}
controller中
//controller中方法
@RequestMapping("/A/info")
~~~@PreAuthorize("@ss.hasPermi('A:info:remove')")@PostMapping("/empty")public AjaxResult empty( String a, String b, Integer c) {return aInfoService.empty(a, b, c);}
方法二:json-同ui前后端交互
如果想要ruoyi-ui的前后端表单交互与ruoyi-app使用前后端表单交互相同,需要对request.js进行修改
修改ruoyi-ui的request.js
方法一:axios请求配置中提供了transformRequest方法用于发送前修改请求数据
请求配置 | Axios中文文档 | Axios中文网 (axios-http.cn)
创建axios实例后,添加
// 新增
// `transformRequest` 允许在向服务器发送前,修改请求数据
// 它只能用于 'PUT', 'POST' 和 'PATCH' 这几个请求方法
// 数组中最后一个函数必须返回一个字符串, 一个Buffer实例,ArrayBuffer,FormData,或 Stream
service.defaults.transformRequest = [function (data, headers){if (headers['Content-Type'] === 'application/x-www-form-urlencoded') {return typeof data === 'object' ? qs.stringify(data) : data;}if (headers['Content-Type'].includes("application/json")) {return typeof data === 'object' ? JSON.stringify(data) : data;}return data
}]
方法二:request拦截器中添加,用于修改config.data值
import qs from 'qs'
// 【如果是表单类型,判断一下数据是不是对象,如果是对象,则序列化,如果不是对象则直接返回,如果不是表单则直接返回】
//qs.stringify会将对象序列化为 key1=value1&key2=value2&key3=value3形式
config.data = config.headers['Content-Type'] === "application/x-www-form-urlencoded" ?(typeof config.data === 'object' ? qs.stringify(config.data) : config.data) : config.data;