【问题标题】:Unexpected token S in JSON at position 0 from Spring response来自 Spring 响应的位置 0 的 JSON 中的意外令牌 S
【发布时间】:2019-12-18 12:37:33
【问题描述】:

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

【问题讨论】:

    标签: java angular spring spring-boot angular8


    【解决方案1】:

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

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

    编辑: 请看一下这个以查看示例Spring MVC - How to return simple String as JSON in Rest Controller

    【讨论】:

    • 我再次尝试使用 @PostMapping(path = "/upload",produces = {MediaType.APPLICATION_JSON_VALUE}) 但它不起作用。知道为什么吗?
    • 因为你没有改变任何东西。您是否创建了这样的 StringResponse 对象: public class StringResponse { private String response;公共 StringResponse(String s) { this.response = s; } // 获取/设置省略... } 然后返回 ResponseEntity
    • 不,如果可能的话,我想避免
    • 好的,然后将此 MediaType.APPLICATION_JSON_VALUE 更改为 MediaType.TEXT_PLAIN,因为您要返回 String,而不是 json。您必须告诉 Angular 将返回什么,以便它可以使用它。
    • 你的端点应该看起来像@PostMapping(path = "/upload",produces = {MediaType.TEXT_PLAIN)
    猜你喜欢
    • 2020-08-04
    • 2017-10-26
    • 2016-12-13
    • 1970-01-01
    • 2022-10-24
    • 2021-10-14
    • 1970-01-01
    • 2020-02-05
    • 2021-09-12
    相关资源
    最近更新 更多