javascript - 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(); }
提前感谢您提供的任何建议!
解决方案
您是否也像这样调用 getNumStudents() :
await getNumStudents()
推荐阅读
- vb.net - 使用 webclient vb.net 下载页面 Txt
- php - 上传的文件没有到请求的文件包中
- c# - 如何通过 mvvm 将 wpf 数据网格绑定到包含组合框和测试框组合的列
- python - 如何在 Python 中的 Google 自定义搜索中找到 JSON 结果中的值
- r - 如何控制 ggplot2 图例中包含的几何图形?
- r - 功能“merge_eurostat_geodata”在 Eurostat 版本 3.3.52 中不可用
- javascript - 具有最小和最大数字的输入值
- python-asyncio - 如何为我的聊天室模型编写异步输入函数?
- neo4j - Neo4j 计算两个查询结果之间的增量
- apache-spark - PySpark - 在数组列上加入两个数据框(顺序无关紧要)