質問
はじめてfetch
を使ったのですが色んなサンプルコードをコピってもうまくいきません。
試したコードのうち一つがこれですが、res.json()
のところでどうしてもSyntaxError: Unexpected end of JSON input
となります。
いろいろ書き方を変えたりしたのですが解消せず、、
javascript
1const fetchtest = async (credentials) => { 2 const url = "https://test.local/authenticate"; 3 const data = await fetch(url, { 4 method: 'POST', 5 headers: { 6 'Content-Type': 'application/json' 7 }, 8 body: JSON.stringify(credentials) 9 }).then(res=>res.json()); // これがエラー「Uncaught (in promise) SyntaxError: Unexpected end of JSON input」 10}; 11 12fetchtest({ 13 username: "test", 14 password: "test", 15}); 16
ブラウザの開発者ツールでレスポンスのペイロードを見ようとしたのですがThis request has no response data available.
となってしまっています。ただ、サーバー側のログを見るとちゃんと200で返していて特にエラーにはなっていないです。
XMLHttpRequestを使うと何の問題もなく処理できるので、レスポンスはちゃんとJSONで返ってると思います。
こちらのコードだとブラウザの開発者ツールでもJSONの中身がちゃんと見れました。
javascript
1var xhttp = new XMLHttpRequest(); 2xhttp.onreadystatechange = function() { 3 if (this.readyState == 4) 4 if (this.status == 200) { 5 console.log(xhttp.responseText); // {"message": "OK"} のJSONレスポンス 6 } 7 } 8}; 9xhttp.open("POST", "https://test.local/authenticate", true); 10xhttp.send({ 11 username: "test", 12 password: "test", 13});
参考ですが、サーバー側はFlaskでこれを返してるだけです
python
1# Python3.8 2return Response( 3 response=json.dumps({"message": "OK"}), 4 status=200, 5 mimetype='application/json' 6)
回答2件
あなたの回答
tips
プレビュー