Ruoyi 前后端分离版POST
发送表单
在若依的前后端分离版本中,如果前端向后端发送请求,使用默认的request()
方法,则默认发送Content-Type:application/json
类型的数据,例如:
export function addData(data) {
return request({
url: '/add',
method: 'post',
data: data
})
}
想要发送application/x-www-form-urlencoded
表单数据,需要手动指定headers
中Content-Type
为application/x-www-form-urlencoded
,且需要将数据处理为key=value&key=value
形式的字符串。
将数据处理为key=value&key=value
形式的字符串的方式有两种:
- 将数据处理成
key=value&key=value
形式的字符串后传入request()
方法(影响范围小)
使用axios
库内置的qs
模块中的qs.stringify()
方法,将传入的数据处理成字符串。
例如:
import qs from 'qs' // 如果axios库未内置qs模块,需单独引入
function demo() {
let user = {
name:"tom",
userId:123
}
const encodedData = qs.stringify(user);
// encodeData:"name=tom&userId=123"
return request({
url: '/user',
method: 'post',
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
},
data: encodedData,
})
}
- 在
request()
方法中转换(比较彻底,推荐!)
首先,打开request.js
文件中,添加对qs
的引用
import qs from 'qs'
然后在下图中的位置添加这些代码
// 添加对application/x-www-form-urlencoded类型请求的预处理
service.defaults.transformRequest = [function (data, headers) {
if (headers['Content-Type'].includes('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
}]
后端接受表单数据的示例代码:
@PostMapping("/user")
public Result user(String name, int userId) {
// 处理请求数据
// ...
return Result.success();
}