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
  • 717
  • 2
  • 18
  • 32

4 Answers4

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
  • 54,797
  • 15
  • 112
  • 146
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
1

You need to use Response.text() method

 let response = await this.getDecryptedText(this.entry.text, this.user.userId)
  .then(res=>{
    if(res.ok){
      console.log(res.text())
    }
      

This might work. res.ok there is a boolean which says was request successful or not. You must use this because construction if(res) is useless — you always get response even if request failed.

0

try to print like

console.log(response.body)  

Because, you are getting body in your response.

Pharsa Thapa
  • 326
  • 1
  • 9