首页 > 解决方案 > React 无法使用对 GET 请求的响应

问题描述

我正在使用 React 开发 webapp 的前端,在处理调用响应时遇到了一个奇怪的问题。

我这样打电话:

async getNumStudents() {
    const n = await fetch('http://localhost:8080/students',
        {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        }).then(response => response.json())
          .then((responseJSON) => responseJSON.length);
    console.log(typeof(n));
    console.log(n);
    this.setState({numStudents: n})
    //return n;
}

响应似乎完全符合console.log()s,typeof()返回的“数字”和 JSON 在第二个中显示应该如此,但是如果我尝试返回 n 或将其分配给[object Promise]返回的状态。

如果我没有包含,我会期待这一点,await但我不确定为什么当它退出函数时,值似乎会变成一个承诺。

作为参考,此端点的 Java 代码如下所示:

@CrossOrigin(origins = "http://localhost:3000")
@GetMapping("/students")
public List<Student> getAllStudents() { return studentRepository.findAll(); }

提前感谢您提供的任何建议!

标签: javascriptreactjsrest

解决方案


您是否也像这样调用 getNumStudents() :

await getNumStudents()

推荐阅读