React前端调用Spring Boot后端/toys/addtoy接口返回400错误求助
嘿,你的400 Bad Request错误大概率是前端请求的格式或参数不符合后端预期导致的,我帮你梳理几个关键问题点和对应的修复方案:
1. 别手动设置multipart/form-data的Content-Type
在你的React addToy方法里,手动指定了Content-Type: multipart/form-data; boundary=%%,但当你用FormData作为请求体时,浏览器会自动生成正确的Content-Type头(包括自动生成的boundary分隔符),你手动设置的boundary和实际请求的完全不匹配,这会直接导致后端无法解析你的请求体。另外,Access-Control-Allow-Origin是后端响应需要返回的头,前端请求里加这个完全没用,反而画蛇添足。
修改后的addToy代码:
export const addToy = toy => { const requestOptions = { mode: 'cors', method: 'POST', // 删掉手动加的Content-Type和Access-Control-Allow-Origin body: toy }; fetch(`${API}/toys/addtoy`, requestOptions) .then(response => { if(response.status === 200) console.log('Toy Inserted'); console.log('Response : ', response); // 建议加个错误处理,把后端返回的错误信息打出来,方便排查 if (!response.ok) { return response.text().then(errMsg => { throw new Error(errMsg) }); } }) .catch(err => { console.log('Error while inserting toy : ', err); }) }
2. 对齐前后端的参数类型
后端接口里availability是Boolean类型,虽然Spring Boot能自动把字符串"true"/"false"转成Boolean,但你直接传JS布尔值的话,FormData会把它转成字符串"true"或"false",稳妥起见手动转成字符串更保险;另外toyPrice是Long类型,你前端不用转成Number,直接传字符串就行,Spring Boot会自动处理。
修改handleSubmit里的参数拼接:
const handleSubmit = e => { e.preventDefault() // 先检查文件是否存在(可选,根据业务需求) if (!image) { alert('请选择玩具图片'); return; } let formData = new FormData() formData.append('toyName', toyName) formData.append('toyDescription', toyDesc) // toyPrice直接传原字符串,后端会自动转成Long formData.append('toyPrice', toyPrice) formData.append('quantity', toyQty) // 把布尔值转成字符串形式的"true"/"false" formData.append('availability', (parseInt(toyQty) > 0).toString()) formData.append('file', image) // sellerId也转成字符串,避免类型问题 formData.append('sellerId', loggedIn.loggedInUser.userId.toString()) addToy(formData) }
3. 处理文件参数的必填性
后端的file参数默认是必填的(required=true),如果业务允许不传文件,可以修改后端接口把file设为可选:
@RequestParam(value = "file", required = false) MultipartFile file
同时要在后端代码里处理file为null的情况,比如设置玩具图片时加判断,避免空指针异常:
if (file != null) { toy.setToyImage(ImageEncoderDecoder.compressBytes(file.getBytes())); toy.setImageName(file.getOriginalFilename()); }
4. 查看后端日志精准定位问题
如果以上修改后仍然报错,一定要去看Spring Boot的控制台日志!里面会有非常详细的错误原因,比如“哪个参数缺失”“类型转换失败”之类的,这是最快定位问题的方式。
举个例子,日志可能会显示:
Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required request parameter 'file' for method parameter type MultipartFile is not present]
或者
Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Boolean'; nested exception is java.lang.IllegalArgumentException: Invalid boolean value: ...]
根据这些日志就能直接找到问题所在。
内容的提问来源于stack exchange,提问作者Sushil Shinde

