当前位置: 首页 > 知识库问答 >
问题:

com.fasterxml.jackson.core.jsonParseException:无法识别的标记“hello”:需要(JSON字符串、数字、数组)

葛胜泫
2023-03-14

我有问题发送React多部分表单数据到后端MySQL使用Java。当我在Postman中分别测试React和Java时,它工作得很好。当我使用表单将用户数据和图片从前端发送到后端时,我会出现无法识别的令牌错误。我对这个错误研究了很多,似乎找不到解决办法。请帮助我哪里出了问题。

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))

}
 @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);
        }
    }
 @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;

共有1个答案

冯沛
2023-03-14

Axios发送的请求头有问题。您必须编辑请求,将headerContent-Type设置为Multipart/Form-Data:

const config = {
    headers: {
        'content-type': 'multipart/form-data'
     }
 }

并向axios POST请求添加类似于第三个paramter的配置:

Axios.post("/new/sale", data , config).then(res => console.log(res))
.catch(err => console.log(err))
 类似资料: