1. ホーム
  2. javascript

[解決済み] fetch は空のレスポンスボディを返す

2023-01-24 03:52:02

質問

react/reduxのアプリケーションで、サーバーに簡単なGETリクエストをしようとしています。

fetch('http://example.com/api/node', {
  mode: "no-cors",
  method: "GET",
  headers: {
    "Accept": "application/json"
  }
}).then((response) => {
  console.log(response.body); // null
  return dispatch({
    type: "GET_CALL",
    response: response
  });
})
.catch(error => { console.log('request failed', error); });

問題は、レスポンスボディが空で .then() 関数の中で、レスポンスボディが空になっていることで、その理由がよくわかりません。オンラインで例をチェックしたところ、私のコードは動作するはずなので、明らかにここで何かを見逃しているようです。 問題は、Chrome の開発ツールでネットワーク タブをチェックすると、要求が行われ、私が探しているデータを受信することです。

どなたか、この件に光を当てていただけませんか?

EDITです。

レスポンスの変換をやってみました。

を使って .text() :

fetch('http://example.com/api/node', {
  mode: "no-cors",
  method: "GET",
  headers: {
    "Accept": "application/json"
  }
})
.then(response => response.text())
.then((response) => {
  console.log(response); // returns empty string
  return dispatch({
    type: "GET_CALL",
    response: response
  });
})
.catch(error => { console.log('request failed', error); });

であり .json() :

fetch('http://example.com/api/node', {
  mode: "no-cors",
  method: "GET",
  headers: {
    "Accept": "application/json"
  }
})
.then(response => response.json())
.then((response) => {
  console.log(response.body);
  return dispatch({
    type: "GET_CALL",
    response: response.body
  });
})
.catch(error => { console.log('request failed', error); }); // Syntax error: unexpected end of input

chromeの開発ツールで見てみると

どのように解決するのですか?

こんなことに遭遇しました。この中にあるように 答え を使用すると mode: "no-cors" を使うと opaque response というように、ボディにデータを返さないようです。

opaqueです。クロスオリジンリソースへの "no-cors" リクエストに対するレスポンスです。 厳しく制限される .

私の場合は Express . インストール後 をインストールした後、Express 用の をインストールして設定し mode: "no-cors" , プロミスを返されました。レスポンスデータは、プロミスの中にある、例えば

fetch('http://example.com/api/node', {
  // mode: 'no-cors',
  method: 'GET',
  headers: {
    Accept: 'application/json',
  },
},
).then(response => {
  if (response.ok) {
    response.json().then(json => {
      console.log(json);
    });
  }
});