【问题标题】:How Read Response Promise value from a get service (Springboot) in React?如何从 React 中的 get 服务(Springboot)读取响应承诺值?
【发布时间】:2020-03-20 14:25:30
【问题描述】:

我是 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 作为文本获取?

谢谢 问候

【问题讨论】:

    标签: javascript java reactjs spring-boot


    【解决方案1】:

    您在代码中使用了async await。你不需要链接承诺。 试试这个

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

    此外,您的 fetch 函数应该是 async 函数,以便使用异步等待。

    【讨论】:

    • 是的,但我没有收到文本。我查看此内容:响应 {type:"cors", url:"127.1.1.12:8090/startTest/Test/…", redirected: false, status: 200, ok: true, ...}
    • 您得到的结果类型是什么?你应该可以通过 console.log(result.json()) 使用它
    • 响应类型“corse”我需要将正文作为文本.. 像 Sping Boot 响应
    • Uncaught (in promise) SyntaxError: Unexpected token T in JSON at position 0 如果你看到 springboot 函数,我在正文中放了一个字符串:return ResponseEntity.status(HttpStatus.OK).body(response);
    • 如果你的后端发送字符串,使用console.log(result.text())
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-08
    • 2015-04-12
    • 1970-01-01
    • 2020-11-01
    • 2016-09-19
    • 2021-09-15
    • 1970-01-01
    相关资源
    最近更新 更多