1

I am sending a request to backend with fetchApi and the response is coming as a just only string (not in a json body)

Here is my frontend code:

        async decryptText() {
    let response = await this.getDecryptedText(this.entry.text, this.user.userId)
    if(response){
        console.log(response)
    }
   }
        
async getDecryptedText(inputText: string, userId: number) {
    let url = "http://localhost:8080/getDecryptedText?textToDecrypt=" + inputText + "&userId=" + userId;
    return fetch(url);
  }

But I cannot parse the response like other json responses because it is just a string.

When I print it to console the output is this: enter image description here

I just want to print on to console the response string

How can I get the string response and assign it to a variable ?

I have edited the code as on answers.

Chris Garsonn
  • 605
  • 11
  • 24

3 Answers3

2

await means wait until promise is resolved. so you should not use .then callback function. It should be,

async decryptText() {
     let response = await this.getDecryptedText(this.entry.text, this.user.userId)

     // promise is resolved here with success or failure

     if(response){
         console.log(response)   // you should get result here
     }
}
micronyks
  • 52,386
  • 15
  • 100
  • 135
1

hope it help's you try this :

  decryptText() {
   this.getDecryptedText(this.entry.text, this.user.userId)
     .then(response => response.json())
     .then(response => {
     console.log(response)
     })
   }
getDecryptedText(inputText, userId) {
 let url = "http://localhost:8080/getDecryptedText?textToDecrypt=" + inputText + "&userId=" + userId;
        return fetch(url);
  }
  • Uncaught (in promise): SyntaxError: Unexpected token a in JSON at position 0 SyntaxError: Unexpected token a in JSON at position 0 – Chris Garsonn Jul 28 '20 at 12:37
0

try to print like

console.log(response.body)  

Because, you are getting body in your response.

Pharsa Thapa
  • 316
  • 1
  • 9