You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native项目JSON Parse报错:Unrecognized token '<' 求助

Hey there! Let's break down why you're hitting that JSON parse error even though the response text looks like valid JSON.

That "Unrecognized token '<'" error typically pops up when the server returns non-JSON content (like an HTML error page), but you mentioned response.text() gives you the correct JSON string. The most likely culprit here is the response Content-Type header from your server.

Fetch's response.json() method doesn’t just blindly parse the text as JSON—it first checks if the response’s Content-Type header is set to something like application/json. If the server sends back a different header (e.g., text/plain, text/html, or even omits it entirely), response.json() might refuse to parse the content correctly, throwing that error even if the text itself is valid JSON.

Solution 1: Manually parse the text response

Since you know the text is valid JSON, skip the response.json() method and parse it yourself after fetching the raw text:

fetch('https://app.fr', {
  method: 'POST',
  headers: new Headers({
    'Content-Type': 'application/x-www-form-urlencoded',
  }),
})
.then((response) => response.text())
.then((rawText) => {
  try {
    const jsonData = JSON.parse(rawText);
    // Handle your parsed JSON data here
    console.log('Parsed data:', jsonData);
  } catch (parseError) {
    console.error('Failed to parse JSON:', parseError);
  }
})
.catch(fetchError => {
  console.error('Fetch request failed:', fetchError);
});

Solution 2: Fix the server's Content-Type header

The cleaner long-term fix is to update your server to send the correct header when returning JSON. Make sure it sends:

Content-Type: application/json; charset=utf-8

Once the server sets this header, response.json() will work exactly like it did in your previous projects.

Bonus: Debug the response headers

If you want to confirm what header the server is actually sending, add a quick log to check:

fetch('https://app.fr', {
  method: 'POST',
  headers: new Headers({
    'Content-Type': 'application/x-www-form-urlencoded',
  }),
})
.then((response) => {
  console.log('Server Content-Type:', response.headers.get('Content-Type'));
  return response.text();
})
.then(rawText => JSON.parse(rawText))
// ... rest of your code

内容的提问来源于stack exchange,提问作者Romain Carlino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:27:31