javascript - 为什么在浏览器中访问 URL 时 axios.get 为空,而 URL 工作正常?
问题描述
import axios from 'axios';
const URL = 'http://localhost:5000/api/posts/';
class PostService {
static getPosts() {
return new Promise( (resolve, reject) => {
try {
const res = axios.get(URL);
const data = res.data;
resolve(
data.map(post => ({
...post,
createdAt: new Date(post.createdAt)
}))
)
}
catch (e) {
reject(e);
}
});
}
运行时出现“TypeError: Cannot read property 'map' of undefined”的错误。事实证明,变量data
为空。但是,当我在浏览器中访问 URL 时,数据完美显示如下:
数据截图
有人能告诉我为什么吗?谢谢~
解决方案
在引用它之前,您无需等待 .get 函数调用解析。在异步函数中,您可以等待它,但在承诺中,您必须将异步任务放在 .then()
编辑:也许这不清楚,
尝试:
import axios from 'axios';
const URL = 'http://localhost:5000/api/posts/';
class PostService {
static getPosts() {
return new Promise( (resolve, reject) => {
axios.get(URL)
.then(res => resolve(res.data.map(post => ({
...post,
createdAt: new Date(post.createdAt)
}))))
.catch(reject)
});
}
推荐阅读
- java - 使用 jOOλ 按属性汇总 BigDecimal 分组
- python - 如何在pygame中反映屏幕
- javascript - 如何将数组分成随机对数组(不重复)?
- django - 无法使用 djangocms-filer 选择图像文件
- c++ - 有人可以解释一下,为什么我的代码不起作用?
- javascript - 在javascript中使用数组查找最大数
- neo4j - Neo4j - Cypher 节点和关系关系
- c# - 为什么有些文本是粗体的?
- cassandra - Cassandra 无效查询:缺少一些集群键
- javascript - 链接上的 e.preventDefault() 仍会加载页面