Javascript 为什么抓取(API)给我未定义的?

Javascript 为什么抓取(API)给我未定义的?,javascript,ecmascript-6,Javascript,Ecmascript 6,我使用Flask创建了一个API,当在Postman中使用它时,它工作得非常好,给了我JSON。 无论如何,当我尝试用javascript获取它时,它给了我未定义的: api='1〕http://127.0.0.1:5000/'; 常量getData=()=>{ 获取(api) 。然后(响应=>{ json(); }) 。然后(数据=>{ 控制台日志(数据); }); }; getData(); 正如我所说,当我尝试记录数据时,它会打印出来 未定义 您需要返回json数据(return res

我使用Flask创建了一个API,当在Postman中使用它时,它工作得非常好,给了我JSON。 无论如何,当我尝试用javascript获取它时,它给了我未定义的:

api='1〕http://127.0.0.1:5000/';
常量getData=()=>{
获取(api)
。然后(响应=>{
json();
})
。然后(数据=>{
控制台日志(数据);
});
};
getData();
正如我所说,当我尝试记录数据时,它会打印出来

未定义

您需要返回json数据(
return response.json();
),修复了代码段:

api='1〕http://127.0.0.1:5000/';
常量getData=()=>{
获取(api)
。然后(响应=>{
返回response.json();
})
。然后(数据=>{
控制台日志(数据);
});
};
getData();

由于不返回任何内容,因此未定义。如果不返回某个内容,则每个函数都返回未定义

api = 'http://127.0.0.1:5000/';

const getData = () => {


fetch(api)
  .then(response =>{

     return response.json();

    })
.json()
也是异步的,因此在调用ur函数后需要一个
.then()

getData().then( res => {
   console.log(res);
});

您的第一个
then
原因没有返回值,请删除括号或在
response.json()前面添加
return
,或者您可以使用
then(response=>response.json())