Javascript 如何获取fetch api的字符串响应并将其分配给变量?

Javascript 如何获取fetch api的字符串响应并将其分配给变量?,javascript,angular,typescript,fetch,fetch-api,Javascript,Angular,Typescript,Fetch,Fetch Api,我正在用fetchApi向后端发送一个请求,响应是作为唯一的字符串(而不是json正文) 这是我的前端代码: async decryptText() { let response = await this.getDecryptedText(this.entry.text, this.user.userId) if(response){ console.log(response) } } async getDecryp

我正在用fetchApi向后端发送一个请求,响应是作为唯一的字符串(而不是json正文)

这是我的前端代码:

        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);
  }
但是我不能像其他json响应那样解析响应,因为它只是一个字符串

当我将其打印到控制台时,输出如下:

我只想打印到控制台上以控制响应字符串

如何获取字符串响应并将其分配给变量


我已将代码编辑为答案。

等待表示等待承诺得到解决。所以你不应该使用
。那么
回调函数。应该是,

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
     }
}

希望它能帮助您尝试以下方法:

  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);
  }
尽量像印刷品一样印刷

console.log(response.body)  

因为,您的响应中包含正文。

如果不是JSON,则不要调用
response.JSON()
。另外
getDecryptedText()
未声明为
async
,因此您不能
等待它。如果使用Angular,您也可以尝试。它有点多功能。我已经编辑了代码和输出。我仍然无法将其打印到控制台。我已经编辑了代码和输出。我仍然无法将其打印到控制台
cosonole.log(响应)
它打印什么?未捕获(承诺中):语法错误:位置0处JSON中的意外标记a语法错误:位置0处JSON中的意外标记a不起作用:(它以可读流的形式打印整个身体检查一些api测试平台上的api,如,postman,并向我们显示结果。我希望这能解决您的问题