简体   繁体   中英

Unexpected token S in JSON at position 0 from Spring response

I want to upload a file from Angular to Spring. I tried this:

@PostMapping(path = "/upload", produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> uploadData(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) throws Exception {

    ......
    return new ResponseEntity<>(originalName, HttpStatus.OK);
}

Angular code:

const formData = new FormData();
formData.append('file', file, file.name);
return this.http.post(environment.api.urls.merchants.uploadLogo, formData);

But I get error:

message: "Unexpected token S in JSON at position 0"
stack: "SyntaxError: Unexpected token S in JSON at position 0↵    at JSON.parse (<

I suppose that Spring has to return JSON response, but for some reason it's not working.

Do you know how I have to configure the Spring endpoint properly?

EDIT I tried this:

@PostMapping(path = "/upload", produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<String> uploadData(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) throws Exception {
    ......
    return new ResponseEntity<>(originalName, HttpStatus.OK);
}

Your endpoint should produces="text/plain" because you are returning String not a json object. Angular on the other hand is expecting json and therefore you are getting that kind of message.

If you want to return json, create wrapper around that string message.

EDIT: Please take a look at this to see example Spring MVC - How to return simple String as JSON in Rest Controller

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