首页 > 解决方案 > 如何获取 fetch api 的字符串响应并将其分配给变量?

问题描述

我正在使用 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 响应那样解析响应,因为它只是一个字符串。

当我将其打印到控制台时,输出是这样的: 在此处输入图像描述

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

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

我已将代码编辑为答案。

标签: javascriptangulartypescriptfetchfetch-api

解决方案


await意思是等到promise被解决。所以你不应该使用.then 回调函数。它应该是,

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

推荐阅读