简体   繁体   English

来自 Spring 响应的位置 0 处的 JSON 中的意外令牌 S

[英]Unexpected token S in JSON at position 0 from Spring response

I want to upload a file from Angular to Spring.我想将文件从 Angular 上传到 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.我想 Spring 必须返回 JSON 响应,但由于某种原因它不起作用。

Do you know how I have to configure the Spring endpoint properly?您知道我必须如何正确配置 Spring 端点吗?

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.您的端点应该生成 =“text/plain”,因为您返回的是 String 而不是 json 对象。 Angular on the other hand is expecting json and therefore you are getting that kind of message.另一方面,Angular 期待 json,因此您会收到这种消息。

If you want to return json, create wrapper around that string message.如果要返回 json,请围绕该字符串消息创建包装器。

EDIT: Please take a look at this to see example Spring MVC - How to return simple String as JSON in Rest Controller编辑:请看一下这个以查看示例Spring MVC - How to return simple String as JSON in Rest Controller

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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