React Native请求报错:SyntaxError: Unexpected token '<' 如何解决?
问题分析与解决
错误SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON的核心原因:后端返回的是HTML页面(大概率是404错误页),而非你期望的JSON数据,前端调用response.json()解析HTML时就会抛出语法错误。同时你的前端请求还存在格式不匹配的问题,具体修复如下:
1. 修正请求格式不匹配问题
你的请求头设置了Content-Type: multipart/form-data,但请求体用了JSON.stringify()生成的JSON字符串,这两种格式不兼容,二选一调整:
方案A:用JSON格式发送数据(推荐)
将Content-Type改为application/json,保持JSON格式的请求体:
<View style={styles.container}> <TouchableOpacity onPress={() => { fetch(API_URL+'/get', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', // 修正此处的Content-Type }, body: JSON.stringify({ 'name': 'item name', 'description': 'item description', }) }) .then((response) => { // 先检查响应状态,提前拦截非成功响应 if (!response.ok) { throw new Error(`HTTP错误:${response.status}`); } return response.json(); }) .then((responseJson) => { console.log(responseJson); this.setState({ data: responseJson }) }) .catch((error) => { console.error(error); }) }} style={styles.Button}> <Text style={styles.ButtonText}>3abez</Text> </TouchableOpacity> </View>
方案B:用multipart/form-data格式发送数据
如果后端明确要求接收multipart/form-data,需用FormData对象构造请求体:
<View style={styles.container}> <TouchableOpacity onPress={() => { const formData = new FormData(); formData.append('name', 'item name'); formData.append('description', 'item description'); fetch(API_URL+'/get', { method: 'POST', headers: { Accept: 'application/json', // multipart/form-data的边界会由系统自动添加,无需手动设置Content-Type }, body: formData }) .then((response) => { if (!response.ok) { throw new Error(`HTTP错误:${response.status}`); } return response.json(); }) .then((responseJson) => { console.log(responseJson); this.setState({ data: responseJson }) }) .catch((error) => { console.error(error); }) }} style={styles.Button}> <Text style={styles.ButtonText}>3abez</Text> </TouchableOpacity> </View>
2. 检查后端路由配置
确认后端是否存在POST /get的有效路由:
- 如果后端接口路径不是
/get,修改前端请求路径匹配后端实际路由 - 如果后端该路由仅支持GET方法,要么调整前端请求方法为GET(不推荐用GET发送请求体),要么修改后端路由支持POST
3. 调试建议
在解析JSON前先打印后端返回的原始内容,方便定位问题:
.then((response) => { return response.text().then(text => { console.log('后端返回内容:', text); try { return JSON.parse(text); } catch (e) { throw new Error('返回内容不是JSON格式'); } }) })
内容的提问来源于stack exchange,提问作者za3imiscoding
相关产品推荐
相关产品推荐

