javascript - 如何获取 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 响应那样解析响应,因为它只是一个字符串。
我只想打印以控制台响应字符串
如何获取字符串响应并将其分配给变量?
我已将代码编辑为答案。
解决方案
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
}
}
推荐阅读
- android - Android 中 startForeground 错误的错误通知
- python-3.x - 如何查找和替换列表中存在的字典值
- macos - zsh:找不到命令:UI5 vs 代码
- python - 线程还是多处理?返回一个非常大的数组
- c# - 从 c# 连接到 ms 访问时出现语法错误
- assembly - 如何访问命令行参数 (./program arg1 arg2 arg3)
- python-3.x - “冻结”未定义Pylance(reportUndefinedVariable)
- c - 使用 C 使用 Windows 读取传入的串行数据
- fluid-framework - 尝试在根 SharedDirectory 中存储 SharedString 时未注册通道工厂
- bash - Bash: -e 选项从 $@ 消失了