[英]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.