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

Kar*_*pik 4 javascript fetch node.js ecmascript-2016

我有以下用于发出 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}"`));
            });
Run Code Online (Sandbox Code Playgroud)

Jua*_*ado 6

我会用这样的东西。

第一个选项假设您的服务响应始终是标头"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");
});
Run Code Online (Sandbox Code Playgroud)

并且fetchjson 处理应该如下所示。你的代码的其他部分看起来对我来说很好。

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()
});
Run Code Online (Sandbox Code Playgroud)

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