簡體   English   中英

JavaScript提取響應返回未定義

[英]JavaScript fetch response returning undefined

我正在嘗試使用訪存來加載一些服務器數據。 這是代碼:

fetch('/user', {
    method: 'POST',
    headers: {
        Accept: 'application/json',
        'Content-type': 'application/json'
    },
    body: JSON.stringify({
        data: 'test'
    })
})
.then(response => {
        if (response.status !== 200) {
            console.log('Fetch status not OK');
        }
        else {
            console.log('Fetch ok');
            console.log(response); // Undefined here
        }
    })
.catch(error => {
        console.log('network error');
    });

在瀏覽器(網絡)上,我可以看到正在從服務器返回響應負載,但是響應包含undefined 我可以想象這很簡單,但是我無法了解這里發生了什么。

我有一個類似的問題,其中response.body返回undefined 與OP的代碼並不完全相同,但是我猜這可能是相同的問題,並且搜索也導致了我的出現,因此請發布我的答案。

發生這種情況是因為尚未讀取正文,只有響應頭才到達。 訪問響應正文的正確方法是:

fetch('/user').then((resp) => resp.json().then((body) => console.log(body)))

此處記錄了讀取正文的各種方式(如文本,JSON等)。

暫無
暫無

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

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