React fetch获取数据遇JSON输入意外结束错误,求排查及检查方法
Hey there! Let's work through this problem together. That Unexpected end of JSON input error usually pops up when response.json() tries to parse something that isn't valid JSON (or even completely empty content) — even if Postman works, there might be subtle differences in how your fetch request handles the response.
如何检查数据是否完成获取?
Here are a few practical ways to verify if your data is being fetched correctly:
Check the response status first
Fetch doesn't reject on HTTP error statuses (like 404, 500) — it only rejects on network failures. So before parsing JSON, confirm the response is successful:.then(function (response) { console.log('Response status:', response.status); if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } return response.json(); })Inspect the raw response content
Replaceresponse.json()withresponse.text()temporarily to see exactly what the server sends back. This will tell you if the response is empty, malformed, or not JSON at all:.then(function (response) { console.log(response); return response.text(); // Switch to text instead of json }) .then((rawContent) => { console.log('Raw response content:', rawContent); // Try parsing manually to catch errors try { const myJson = JSON.parse(rawContent); this.setState({ myJson: myJson }); } catch (e) { console.error('Failed to parse JSON:', e); } })Add error handling to your promise chain
Always include a.catch()at the end of your fetch chain to catch unhandled errors (like parsing issues) and log them properly:.catch((error) => { console.error('Fetch error:', error); });
你的代码里的问题及修复
Looking at your component, the main gap is missing error handling for the fetch request. Let's fix that, plus add safeguards to avoid the JSON parsing error:
修改后的componentDidMount方法
componentDidMount() { fetch(Constants.API_URL + 'api/user', { method: 'GET', headers: { "Authorization": "Bearer 733a7570-c39a-4fff-99e8-bcc38c1aad58", "Content-Type": "application/json" } }) .then((response) => { console.log('Full response:', response); // Verify the response is successful if (!response.ok) { throw new Error(`Server returned status ${response.status}`); } // Handle empty or invalid JSON gracefully return response.text().then((text) => { if (!text) { throw new Error('Empty response from server'); } try { return JSON.parse(text); } catch (parseError) { throw new Error(`Invalid JSON: ${parseError.message}`); } }); }) .then((myJson) => { this.setState({ myJson: myJson }); console.log('Parsed data:', myJson); }) .catch((error) => { console.error('Fetch failed:', error); // Optional: Set an error state to display to users // this.setState({ error: error.message }); }); }
其他小建议
- In your
deletemethod, you're also using fetch without error handling — adding a.catch()there will help you catch any issues with the delete request. - Double-check that your
Authorizationtoken is still valid — expired tokens can lead to empty or error responses even if Postman worked earlier.
内容的提问来源于stack exchange,提问作者Julius Oscar

