首页 > 解决方案 > React/Express:在响应承诺中插入 if 语句?

问题描述

我收到了从 POST 调用到 express 后端的承诺响应。我想在承诺中插入一个 if 语句,这似乎打破了它。

这有效:

fetch('http://localhost:8000/upload', {
    method: 'POST',
    body: formData,
})
    .then(response =>
        response.json())
    .then(response => {
        console.log(response);
    })

这个 if else 语句破坏了代码:

fetch('http://localhost:8000/upload', {
        method: 'POST',
        body: formData,
    })
        .then(response => {
            if (response.ok) {
                response.json()
            } else {
                throw new Error('Something went wrong ...');
            }
        })
        .then(response => {
            console.log(response);
        })

这样的事情可能吗?提前致谢!

标签: javascriptreactjsexpresspostpromise

解决方案


你没有回到response.json你的if街区。所以,在下一个then方法中你没有response定义。试试这个:

fetch('http://localhost:8000/upload', {
        method: 'POST',
        body: formData,
    })
        .then(response => {
            if (response.ok) {
                return response.json()
            } else {
                throw new Error('Something went wrong ...');
            }
        })
        .then(response => {
            console.log(response);
})

推荐阅读