当用户尝试上传不是图像的文件时,我试图显示来自 REST API 的错误消息。从 API 返回的 JSON 类似于:{
"publicError": "Could not be uploaded, it is not an image!",
"innerError": "WrongImageTypeException()"
}但我不知道它如何向用户显示。我试过了this.setState({ errorMesage: { ...err } })控制台日志看起来像这样https://cdn1.imggmi.com/uploads/2019/4/4/f642ed4326147b3f2c6899e78d415771-full.png。如何显示此响应错误消息?后端代码public ResponseEntity<?> uploadFile( @RequestHeader(value = "Authorization") String authorizationHeader, @RequestParam("file") MultipartFile file) throws UserNotFoundException { try { if(!(fileStorageService.checkFileType(file))){ throw new WrongImageTypeException(); } }catch (WrongImageTypeException error){ return ResponseEntity.status(403).body(new ErrorMessageManager( "Could not be uploaded, it is not an image!",error.toString())); }前端代码this.state : { errorMesage: { publicError: "", }, } public uploadHandler() { const formdata: FormData = new FormData(); formdata.set('file', this.state.avatar); const config = { headers: { 'Content-Type': 'multipart/form-data', 'Authorization': `Bearer ${cookies.get('tk879n')}` } }; axios.post( `${serverUrl}/uploadFile`, formdata, config ).then(response => { this.setState({ userProfile: { ...this.state.userProfile, avatarUrl: response.data, } }); } ).catch((err) => { // i want to set error message state and display in render function this.setState({ errorMesage: { ...err } }); console.debug(this.state.errorMesage); }); }爪哇岛反应打字脚本弹簧靴
1 回答
沧海一幻觉
TA贡献1824条经验 获得超5个赞
您的显示对象的结构:console.debug(this.state.errorMesage);
从结构中,您可以看到 包含您要查找的结构:this.state.errorMesage.response.data
"publicError": "Could not be uploaded, it is not an image!",
"innerError": "WrongImageTypeException()"
修复
所以而不是你应该使用 👍🏻...err...err.response.data
添加回答
举报
0/150
提交
取消