Gen
Gen

Reputation: 2540

post method is not going to success part in angular

I am writing an angular with java project for this I have wrote a java rest service and I am calling it from my angular client with post method. it is able to call the rest service but it is not coming to client side.

I kept an alert in success. It is not printing but in chrome network tab the status is showing 200.

Angular: -

 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 service: -

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

I want to do some functionality in success, but the call is not coming to success part.

I got an error in the console.

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

Upvotes: 1

Views: 91

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71911

You are returning a text and not a JSON object from your java service. You can fix this by specifying the responseType in your post call:

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

You can also think about returning a JSON from your JAVA endpoint, but that's up to you

Upvotes: 1

Related Questions