Vue PUT请求的方式提交数据
一、问题描述:后端的接口用的 PUT 方式,前端的提交数据需要用PUT方式
@RequestMapping(value = "/updateOnePersonById",method = RequestMethod.PUT)
public Boolean updateOnePersonById(@RequestParam Map map){
...
}
如果前端提交的方式和后端指定的方式不一致,经常会出现
Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method ‘PUT’ not supported]
Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method ‘POST’ not supported]
Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method ‘GET’ not supported]
诸如以上的错误,都是提交方式不匹配引起的
二、解决方法:对于 post get 使用对应的提交方式即可;对应 PUT方式,提交的 type 写成 post,再添加一个 _method=PUT 即可
***需要对这个data做处理,在json 串中添加一个属性 ***
Vue 的写法:在 data 中个添加了一个 对象,存放表单数据,提交这个数据的时候,需要添加一个
_method : “PUT”
...
data: {
updateForm: {},
}
...
**//需要对这个data做处理,在json 串中添加一个属性**
this.updateForm['_method'] = 'PUT';
$.ajax({
url: "http://localhost:8080/updateOnePersonById",
type: "post",
data: vm.updateForm,
success: function(result) {
console.log("updateOnePersonByIdMsg", result);
if (result) {
alert("修改成功");
//刷新数据,并停留在当前页
vm.toPage(vm.pageInfo.pageNum);
} else {
alert("修改失败");
}
}
});
三、以上的方法,不用原生的ajax 提交的时候,用下面的方式提交的时候,又不行了
Vue.prototype.$http = axios
const result= await this.$http.put("http://localhost:8080/updateOnePersonById",vm.updateForm);
使用axios 方式提交的时候,有不行了
四、解决方案:
todo…
欢迎大佬提出解决方法
笔者自己的解决方案
1)type 直接写成 put
2)同时设置 contentType:“application/json”,
3)提交的数据转成 json
data:JSON.stringify(vm.updateRoleAndPermission),
4)后端的controller requestMapping 加上 method = RequestMethod.PUT,produces = {“application/json;charset=UTF-8”}
5)参数接收使用 @RequestBody 注解
亲测有效