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

时间:2017-01-09 18:51:40

标签: javascript node.js fetch ecmascript-7

我有以下代码用于发出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}"`));
            });

1 个答案:

答案 0 :(得分:1)

我会用这样的东西。

这个第一个选项总是将服务响应作为标题"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()允许您多次解析相同的响应并创建自己的组合,就像前一个一样。