简体   繁体   中英

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. When I test for React and Java individually in Postman, it works fine. 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

 @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

 @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. You have to edit your request to set header content-type to multipart/form-data :

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

And add this config like 3rd paramter to axios POST request:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM