带有 Promises 的 Javascript Fetch API - 传递 HTTP 响应代码

问题描述 投票:0回答:1

我使用以下代码向我的 API 发出 HTTP 请求:

fetch('api/register', {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
    },
    body: JSON.stringify(jsonObj)
})
    .then(response => {
        responseClone = response.clone();
        if (!response.ok) {
            console.log(`HTTP ERROR STATUS CODE: ${response.status}`);
        }
        return response.json();
    })
    .then(function (data) {
        processDataFromServer(data);
    }, function (rejectionReason) {
        console.log('JSON Parsing Error:', rejectionReason, responseClone);
        responseClone.text()
            .then(function (bodyText) {
                console.log('Cannot parse as JSON:', bodyText);
            });
    })
    .catch(error => {
        console.log("Error: " + error)
        deplayError(error);
    });

代码有效!我想做的唯一更改是将

response.status
传递给我的
processDataFromServer(data)
函数。像
processDataFromServer(data, response.status)
之类的东西。 由于
response.json()
是一个承诺,我无法同时将承诺和属性返回到我的下一个方法。知道如何做到吗?

javascript async-await fetch-api
1个回答
0
投票

如果您将代码重写为

async
函数并使用
await
,将会更容易。像这样的东西:

async function retrieve() {
    try {
        const response = await fetch('api/register', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(jsonObj)
        });
        const responseClone = response.clone();
        if (!response.ok) {
            console.log(`HTTP ERROR STATUS CODE: ${response.status}`);
        }
        try {
            const data = await response.json();
            processDataFromServer(data, response.status);
        } catch (rejectionReason) {
            console.log('JSON Parsing Error:', rejectionReason, responseClone);
            const bodyText = await responseClone.text();
            console.log('Cannot parse as JSON:', bodyText);
        }
    } catch (error) {
        console.log("Error: " + error)
        deplayError(error);
    }
}

retrieve();
© www.soinside.com 2019 - 2024. All rights reserved.