繁体   English   中英

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

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

我想将文件从 Angular 上传到 Spring。 我试过这个:

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

角度代码:

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

但我得到错误:

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

我想 Spring 必须返回 JSON 响应,但由于某种原因它不起作用。

您知道我必须如何正确配置 Spring 端点吗?

编辑我试过这个:

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

您的端点应该生成 =“text/plain”,因为您返回的是 String 而不是 json 对象。 另一方面,Angular 期待 json,因此您会收到这种消息。

如果要返回 json,请围绕该字符串消息创建包装器。

编辑:请看一下这个以查看示例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