[英]com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Hello': was expecting (JSON String, Number, Array,)
I am having problem sending React multipart form data to backend MySQL using Java.我在使用 Java 将 React 多部分表单数据发送到后端 MySQL 时遇到问题。 When I test for React and Java individually in Postman, it works fine.
当我在 Postman 中分别测试 React 和 Java 时,它工作正常。 The problem occurs when I use the form to send the user data along with a picture from frontend to backend, I get Unrecognized token error.
当我使用表单将用户数据以及图片从前端发送到后端时,会出现问题,我收到无法识别的令牌错误。 I have researched this error a lot and can't seem to find the solution.
我已经对此错误进行了很多研究,但似乎找不到解决方案。 Please help where I am going wrong.
请帮助我哪里出错了。
React:反应:
const [firstName, setFirstName] = useState()
const [lastName, setLastName] = useState()
const [email, setEmail] = useState()
const [phoneNumber, setPhoneNumber] = useState()
const [file, setFile] = useState()
const send = event => {
const data = new FormData()
data.append("user", firstName)
data.append("file", file)
Axios.post("/new/sale", data).then(res => console.log(res))
.catch(err => console.log(err))
}
Controller Controller
@PostMapping(value = "/sale")
public ResponseEntity<Response> createPost(@RequestParam("file") MultipartFile file,
@RequestParam("user") String user)
throws IOException {
ObjectMapper obj = new ObjectMapper();
Sale sale = obj.readValue(user, Sale.class);
sale.setPicture(file.getBytes());
sale.setFileName(file.getOriginalFilename());
Sale sales = saleRepository.save(sale);
if(sales != null) {
return new ResponseEntity<Response>(HttpStatus.OK);
} else {
return new ResponseEntity<Response>(HttpStatus.BAD_REQUEST);
}
}
POJO POJO
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String firstName;
private String lastName;
private String email;
private String phoneNumber;
private Date createdDate;
private Date updatedDate;
private byte [] picture;
private String fileName;
You have a problem with the header of the request send by axios.您对 axios 发送的请求的 header 有问题。 You have to edit your request to set header
content-type
to multipart/form-data
:您必须编辑您的请求以将 header
content-type
设置为multipart/form-data
:
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
And add this config like 3rd paramter to axios POST request:并将此配置(如第三个参数)添加到 axios POST 请求:
Axios.post("/new/sale", data , config).then(res => console.log(res))
.catch(err => console.log(err))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.