「これからのための気持ちの整理。 」

これからのことを考えています。本当に、本当にめんどうくさい、めんどくさい人間です。これからのために、気持ちの整理をします。

fetchの返り値をjsonで見れない(SyntaxError: Unexpected token < in JSON at position 0) 場合の処理

function postData(data){
  const res = fetch('xxx',{
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  });
  return res.json();
}
postData('hoge', {status:200, task:2, etc:3}).then(console.log).catch(console.error);
SyntaxError: Unexpected token < in JSON at position 0

Fetchの仕様を確認

developer.mozilla.org

blob()にした後、text()を呼ぶとエラーにならずデータの中身を見れました。

developer.mozilla.org

function postData(data){
  const res = fetch('xxx',{
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  });
  return res.blob();
}
postData('hoge', {status:200, task:2, etc:3}).then(blob=>console.log(blob.text())).catch(console.error);
Promise {<pending>}__proto__: Promise[[PromiseState]]: "fulfilled"[[PromiseResult]]: "<!DOCTYPE html><html><head><l...