描述
在使用Easy-UI框架请求表单数据的UPDATE操作的时候,报了如下入错:
General
Request URL: http://localhost:8280/device/instrument/v1/register
Request Method: POST
Status Code: 415
Remote Address: [::1]:8280
Referrer Policy: no-referrer-when-downgrade
---
Request Headers
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Accept-Encoding: gzip, deflate, br
Accept-Language: zh,en-US;q=0.9,en;q=0.8,zh-CN;q=0.7
Cache-Control: max-age=0
Connection: keep-alive
Content-Length: 103
Content-Type: application/x-www-form-urlencoded
Cookie: JSESSIONID=5576D4BE4E92115773583CDE439C6CDE
Host: localhost:8280
Origin: http://localhost:8280
Referer: http://localhost:8280/device/tag.html
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36
这里重点注意Content-Type: application/x-www-form-urlencoded
,请求格式与后台的不匹配导致415错误。
原因查找
查看easyui的请求UPDATE方法得知,请求代码如下:
$("#fm").form("submit", {url: url,onSubmit: function () {return $(this).form("validate");},success: function (result) {var result = eval('(' + result + ')');if (result.success) {$.messager.alert("系统提示", "保存成功!");resetValue();$("#dlg").dialog("close");$("#dg").datagrid("reload");} else {$.messager.alert("系统提示", result.errorInfo);}}});
而在后台的接口接收方式如下:
@PostMapping("/register")public Object register(@RequestBody @Valid Device device,BindingResult bindingResult) {if (bindingResult.hasErrors()) {return new Response(ErrorCode.RES_NOT_EXIST, bindingResult.getFieldError().getDefaultMessage());}return deviceService.register(device);}
此处,有@RequestBody
,因此获取数据的方式为接收Json串。因此导致这个问题。
解决方法
不使用Easyui原生的form表单UPDATE方法,使用自实现的ajax请求
if($(this).form("validate")){$.ajax({type: "POST",contentType: "application/json",url: url,data: JSON.stringify($("#fm").serializeJSON()),success: function (result) {if(result.error_code == 1000) {$.messager.alert("系统提示", "保存成功!");resetValue();$("#dlg").dialog("close");$("#dg").datagrid("reload");} else {$.messager.alert("系统提示", result.errorInfo);}}})}
后台不做任何改变,由此解决问题。