首页 > 解决方案 > 为什么 fetching(API) 给我未定义?

问题描述

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

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

const getData = () => {
  fetch(api)
    .then(response => {
      response.json();
    })
    .then(data => {
      console.log(data);
    });
};
getData();

正如我所说,当我尝试记录数据时,它会打印

undefined

标签: javascriptecmascript-6

解决方案


您需要返回您的 json 数据(return response.json();),固定片段:

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

const getData = () => {
  fetch(api)
    .then(response => {
      return response.json();
    })
    .then(data => {
      console.log(data);
    });
};
getData();

推荐阅读