获取在 Fetch 中导致 json 解析错误的负载

Get payload that caused json parse error in Fetch

我有以下用于发出 POST 请求的代码。 我不是 100% 确定这里的错误处理,但对我来说重要的是当请求不成功时我得到正文。

我仍然遇到的一个问题是 - 如果服务器响应 200 OK 但无效 json - 我可以记录该负载吗? Fetch 的正确记录方式是什么?

           Fetch(data.notificationUrl, {
                method: 'POST',
                body: post_data,
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then((res) => {

                if (!res.ok) {
                    // Could reject the promise here but than response text wouldn't be available
                    //return Promise.reject(`Response was not OK. Status code: ${res.status} text: ${res.statusText}`);
                    return res.text().then((txt) => `Response was not OK. Status code: ${res.status} text: ${res.statusText}.\nResponse: ${txt}`);
                }
                // response ok so we should return json, could follow https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch and determine the payload type by content-type header...
                return res.json();
            }).then((response) => {

                if (response) {
                    // set result
                    // ...

                    // redirect
                    return reply.redirect(data.redirectUrlDirectory);
                }

                return reply(Boom.preconditionFailed(`Did not reply with correct payload! json:'${JSON.stringify(response)}'`));
            }).catch((err) => {

                return reply(Boom.badData(`Could not notify on url ${data.notificationUrl} about the payment ${id}.\nError: "${err}"`));
            });

我会用这样的东西。

这个第一个选项假设您的服务响应始终是 header "application/json" 和我这样模拟的有效负载简单文本。

var app = new express();
app.get('/valid', function(req, res){
  res.json({ok: "ok"});
});
app.get('/invalid', function(req, res){
  res.json("bad json body");
});

fetch json 处理应该如下所示。你代码的另一部分看起来对我来说不错。

var response2 = res.clone();
return res.json().then((json) => {
    // log your good payload
    try {
      // here we check json is not an object
      return typeof json === 'object' ? json : JSON.parse(json);
    } catch(error) {
       // this drives you the Promise catch
      throw error;
    }    
}).catch(function(error) {
     return response2.text().then((txt) => `Response was not OK. Status code: ${response2.status} text: ${response2.statusText}.\nResponse: ${txt}`);
    //this error will be capture by your last .catch()
});

xxx.clone() 允许您多次解析相同的响应,并像上一个一样创建您自己的组合。