使用 formData 使用 Express 节点获取无效 json 响应正文错误

Use*_*696 6 multipartform-data form-data nsfetchrequest node.js express

我正在尝试从 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);
        });

})
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误

“错误”:“原因无效的 json 响应正文:意外的令牌 < JSON 中的位置 0”

我究竟做错了什么?

tok*_*and 13

调用后会消耗身体.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)
Run Code Online (Sandbox Code Playgroud)


小智 11

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