简述
1、axios的表单提交 ,content-type 默认为 application/json;charset=UTF-8
2、提交数据会附加在payload(以JSON形式)。
3、@ModelAttribute 可以接受表单的数据,但是content-type的类型需要为application/x-www-form。@RequestBody 可以接受表单数据,但是content-type类型需要为application/json。@RequestParam 从URL中接受请求参数。(不用于表单提交)。
@RequestBody 方式
axios的表单提交 ,content-type 默认为 application/json;charset=UTF-8 @RequestBody 可以接受表单数据,但是content-type类型需要为application/json
axios
async post(urlParam: string, data: object = {}, headers: object = {}) {
let url = this.baseUrl + urlParam;
// const data = HttpQuery.tranQuestParam(data);
return new Promise((resolve, reject) => {
Axios.post(url, data, headers).then((res) => {
if (res.data.code === 200) {
resolve(res.data.data);
}
}).catch(
(error) => {
console.log(error.message);
},
);
});
}
一. 按map方式接受
Controller
前端传来的是一个json对象时:{},可以用实体类直接进行自动绑定
public APIResult token(@RequestBody Map map, HttpServletRequest req) {
String username = (String) map.get("username");
String password = (String) map.get("password");
User user = this.userService.findByName(username);
}
二. 直接按实体类接收
前端加上请求头
const headers = {
'content-type': 'application/json',
};
请求body
{
"name":"username",
"password":"123456"}
controller
@RequestMapping(value = "api/login", method = RequestMethod.POST)
public APIResult token(@RequestBody User userInfo, HttpServletRequest req, HttpServletResponse response) {
String username = userInfo.getName();
String password = userInfo.getPassword();
return APIResult.ok();
}
@ModelAttribute
被@ModelAttribute注释的方法会在此controller每个方法执行前被执行,因此对于一个controller映射多个URL的用法来说,要谨慎使用。
前端加上请求头
const headers = {
'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
};
url
http://localhost/api/login?username="sf"&password="sdf"
后端加上@ModelAttribute 注解
@RequestParam 从URL中接受请求参数。(不用于表单提交)。
先将body的数据格式化
static tranQuestParam(data: any) {
const params = new URLSearchParams();
// eslint-disable-next-line no-restricted-syntax
for (const key of Object.keys(data)) {
const value = data[key];
params.append(key, value);
}
return params;
}
再提交
async post(urlParam: string, data: object = {}, headers: object = {}) {
let url = this.baseUrl + urlParam;
let data = HttpQuery.tranQuestParam(data);
return new Promise((resolve, reject) => {
Axios.post(url, data, headers).then((res) => {
if (res.data.code === 200) {
resolve(res.data.data);
} else {
this.toast(`${res.data.code}: ${res.data.message}`);
}
}).catch(
(error) => {
console.log(error.message);
this.toast(this.errorMessage);
},
);
});
}
后端用@RequestParam 接受
@RequestMapping(value = "api/token", method = RequestMethod.POST)
public APIResult token(@RequestParam String username,@RequestParam String password) {
}