簡體   English   中英

在React Fetch調用中從Node API訪問Promise數據

[英]Accessing promise data from Node API inside React fetch call

我正在組裝一個React應用程序,該應用程序使用當前位於本地計算機上的Node / Express REST API中的數據。 我有一個簡單的res.json返回Sequelize對象,並且正在通過我提供的服務來訪問它。 顯然,我最終將使該對象處於state ,但是我目前難以訪問這些值。

const options = {
    method: "POST",
    headers: {
        "Content-Type": "application/x-www-form-urlencoded"
    },
    body: JSON.stringify({email: "matthewharp@gmail.com", password: "M1nerals"})
};
fetch('http://localhost:3000/users/sign_in', options)
    .then(response => console.log(response.json()));

我正在控制台中獲得結果,但是它們被卡在[[PromiseValue]]中。

在此處輸入圖片說明

我必須缺少某種異步步驟,但是我不確定。

json方法返回一個promise,您需要等待它。 這樣:

fetch('http://localhost:3000/users/sign_in', options)
    .then(response => response.json())
    .then(obj => console.log(obj));

您遇到此錯誤是因為response.json()返回了promise。

你需要做fetch('http://localhost:3000/users/sign_in', options) .then(response => response.json()) .then(res => console.log(res));

您需要從fetch調用返回諾言,否則您需要在json諾言中對它進行操作。

const options = {
    method: "POST",
    headers: {
        "Content-Type": "application/x-www-form-urlencoded"
    },
    body: JSON.stringify({email: "matthewharp@gmail.com", password: "M1nerals"})
};
return fetch('http://localhost:3000/users/sign_in', options)
    .then(response => {
         console.log(response.json())
         return response.json()
    }
);

要么...

const options = {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        body: JSON.stringify({email: "matthewharp@gmail.com", password: "M1nerals"})
    };
   fetch('http://localhost:3000/users/sign_in', options)
        .then(response => {
             console.log(response.json())
            response.json().then( result => {
               // whatever you're doing with the data here.
        }
    );

看一下fetch API: https//developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

您需要准備一個單獨的鏈, thenthen鏈接起來以獲取json數據,它將為您提供值。

('http://localhost:3000/users/sign_in', options)
.then(function(response) {
    return response.json();
})
.then(function(myJson) {
    console.log(JSON.stringify(myJson));
});

暫無
暫無

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

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