javascriptjavajsonrestspring-mvc

Unexpected Token in JSON error but I'm using 'produces = "text/plain"'?


I'm getting an error when I call the following function in my web app:

  getUML() {
    const testName = this.formdata.get('testName');
    this.disableDeployCTA = true;
    const params:string = testName + "/txt";
    const url = `http://localhost:8081/bruml/export/${params}`
    this.httpService.generateUML(params).subscribe((response: any) => {
      this.umlText = response.data;
    });
  }

The request is going through a Spring Boot application, using this method:

@GetMapping(value = "/export/{testName}/txt", produces = "text/plain")
public ResponseEntity<String> exportTxt(@PathVariable("testName") String name) {
    UMLClient myClient = new UMLClient(); 
    String txtUML = "";
    byte[] toExport = null; 
    try {
        String fileName = ".\\tempFiles\\" + name;
        myClient.export(name, fileName + ".txt", true);
        
        File txtTemp = new File(fileName + ".txt");
        File file = new File(fileName + ".svg");
        Path filePath = Paths.get(fileName + ".txt");
        Charset charset = StandardCharsets.UTF_8;

        txtUML = new String(Files.readAllBytes(filePath)); 
        if(file.exists() && txtTemp.exists()) {
            file.delete();
            txtTemp.delete();
        }
    }
    catch (Exception e){
        e.printStackTrace();
    }
    return new ResponseEntity<>(txtUML, HttpStatus.OK); 
}

And the generateUML method is below:

  generateUML(params) {
    return this.httpClient.get('http://localhost:8081/bruml/export/'+ params);
  }

And Im getting an error that "Unexpected token @ in JSON." But I don't want it to parse as JSON -- I set the produces attribute to plain text. How can I fix this?

EDIT**

I'm getting this error in the console enter image description here

And these are the details in my network tab in dev tools regarding the request and response: enter image description here

enter image description here enter image description here enter image description here


Solution

  • @anoncomp can you post the request and response from your browser network tab and if you are getting 200 response then we can see what exactly you are getting from the backend. If you are getting the correct response then the problem will be in this line: this.umlText = response.data; as you are expecting response to be an object. You might have to parse response.

    EDIT: are you using Angular? If so, can you try sending the option in a get request with responseType as text as well? For reference: Angular Docs. As by default Angular consider response as JSON:

    From angular documentation:

    The get() call needs the following options: {observe: 'body', responseType: 'json'}.

    These are the default values for those options, so the following examples do not pass the options object.