java - Spring 响应中 JSON 中位置 0 处出现意外标记 S

标签 java angular spring spring-boot angular8

我想将文件从 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);
}

Angular 代码:

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

关于java - Spring 响应中 JSON 中位置 0 处出现意外标记 S,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57452597/

相关文章:

java - 矫枉过正还是适当?

angular - 如何在没有推送/弹出的情况下重定向到带有 ionic 2 的页面

spring - 增加 Grails/Tomcat 事件 HTTP 连接限制

java - 我们可以在Java独立应用程序(Swing)中实现Spring Autowiring 吗

带有变量的 Java Xpath

java - 在 XSLT 和 Java 类之间共享 XPath

Angular 5 - 即使在错误发生后如何保持自动重新编译文件更改(webpack 编译失败)

java - Spring MVC 在每个请求之前检查 session

java - 无法更新卡中显示的值 - Android 的 Cardslib 库

angular - 我们在 mat-tooltip 中没有动态内容选项吗?