首页 > 解决方案 > 如何从 React 中的 get 服务(Springboot)读取响应承诺值?

问题描述

我是 reactjs 的新手:我有一个带有一个服务的 springboot,它返回一个像这样的 ResponseEntity:

@RequestMapping(value = "/startTest") 
public ResponseEntity<String> runTest {

    String response;
    if (this.values>0){
        response=String.format("Test Failed: %s", summary.getFailures().get(0).getException().getMessage());
    }
    else{
        response="Test Successfull!";
    }

    return ResponseEntity.status(HttpStatus.OK).body(response); 

在反应中,我有这个功能用于读取正文:

    var url = "http://127.22.22.12:8090/startTest";
    await fetch(url)
        .then(function(response){return response.json();})
        .then(function(data){const items=data;
                             console.log(items)
        })

但我在控制台中有这个错误:

Uncaught (in promise) SyntaxError: Unexpected token T in JSON at position 0

如果写 console.log(response.text()) 我查看 Promise OBJECT 但如何将 PROMISE VALUE 作为文本?

感谢和问候

标签: javascriptjavareactjsspring-boot

解决方案


您在代码中使用异步等待。你不需要链接承诺。尝试这个

 var url = "http://127.22.22.12:8090/startTest";
 const result = await fetch(url)
 console.log(result.text())

此外,您的 fetch 函数应该是一个async函数,以便使用 async await。


推荐阅读