首页 > 解决方案 > post 方法不会在 Angular 中成功

问题描述

我正在为此编写一个带有 java 的 angular 项目我已经编写了一个 java rest 服务,并且我正在使用 post 方法从我的 angular 客户端调用它。它能够调用其余的服务,但它不会到达客户端。

我成功地保持了警惕。它没有打印,但在 chrome 网络选项卡中,状态显示为 200。

角度:-

 uploadFileToActivity() {
   const endpoint = 'http://localhost:8090/sendmails';
   let config =  {headers: new  HttpHeaders({})};
   const formData: FormData = new FormData();
   formData.append('fileupload', this.fileToUpload);
      
   this.httpClient.post(endpoint, formData).subscribe(data => {
   alert();
   })
  }

Java服务:-

    @PostMapping(value = "/sendmails", headers = "content-type=multipart/*")
    public ResponseEntity<String> sendEmails(@RequestParam("fileupload") MultipartFile ExcelDataFile) {
        return new ResponseEntity<String>("Success", HttpStatus.OK);
    }

我想成功地做一些功能,但调用并没有成功。

我在控制台中遇到错误。

error: {error: SyntaxError: Unexpected token S in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt…, text: "Success"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure during parsing for http://localhost:8090/sendmails"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:8090/sendmails"
__proto__: HttpResponseBase

标签: javaangularspring-boot

解决方案


JSON您正在从您的 java 服务返回一个文本而不是一个对象。responseType您可以通过在调用中指定来解决此问题post

this.httpClient.post(endpoint, formData, { responseType: 'text' })

您还可以考虑从您的 JAVA 端点返回 JSON,但这取决于您


推荐阅读