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;