使用 formData 的 Express 节点获取无效 json 响应主体错误

invalid json response body error with Express node-fetch using formData

我正在尝试从 nodeJS 发出 http 请求,这是以下请求:

    const form = new FormData();
    form.append('text 1', 'sometext');
    form.append('file', fs.createReadStream("foo.txt"));
    fetch('url', {
            method: 'POST',
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            body: form,
        })
        .then(res => res.json())
        .then(json => {
            console.log('res', json);
        }).catch(err => {
            console.error(err);
            return ReE(res, err.message, 500);
        });

})

但是我收到以下错误

"error": "invalid json response body at reason: Unexpected token < in JSON at position 0"

我做错了什么?

在您的第一个 .then() 块中尝试 res => console.log(res) 以查看响应是什么。通常那个错误 "Unexpected token < in JSON..." 意味着响应返回了一些 html 而错误中的“<”是一个开始标记。

调用.json()后,正文被消耗掉了,不确定之后是否可以访问它。一个简单的解决方法:获取原始正文并自行解析:

async function safeParseJSON(response) {
    const body = await response.text();
    try {
        return JSON.parse(body);
    } catch (err) {
        console.error("Error:", err);
        console.error("Response body:", body);
        // throw err;
        return ReE(response, err.message, 500)
    }
}

const json = await = fetch(...).then(safeParseJSON)