簡體   English   中英

為什么 fetching(API) 給我未定義?

[英]Why fetching(API) gives me undefined?

我使用 Flask 創建了一個 API,在 Postman 中使用它時它工作得很好,給了我 Z0ECD11C1D7A2874018DBB1。 無論如何,當我嘗試在 javascript 中獲取它時,它給了我未定義:

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

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

正如我所說,當我嘗試記錄數據時,它會打印

undefined

您需要返回您的 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();

你得到未定義,因為你不返回任何東西。 如果您不return某些內容,則每個 function 都會返回 undefined 。

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

const getData = () => {


fetch(api)
  .then(response =>{

     return response.json();

    })

.json()也是異步的,所以在你的 function 調用之后你需要一個 .then .then()塊。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM