所以我是 React Native 的新手,我正在尝试将数据从我的应用程序发送到我的后端,并在我的后端控制台上 siplay 该数据。
问题:我不断收到此错误:
语法错误:意外的标记'<', "
到处寻找如何解决这个问题,但没有任何效果......
这是从我的前端发送数据的部分:
<View style={styles.container}>
<TouchableOpacity onPress={ () => {
fetch(API_URL+'/get', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body:JSON.stringify({
'name': 'item name',
'description': 'item description',
})
})
.then((response) => 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>
我期待在我的控制台上看到: {'name' : '商品名称'}
服务器似乎返回的是 HTML 而不是 JSON。这就是为什么您会收到“意外令牌”<'" error, because the HTML is not valid JSON.
这是一个工作代码示例,用于将数据从 React Native 应用程序发送到后端并在控制台中显示响应数据:
import React, {Component} from 'react';
import {View, TouchableOpacity, Text} from 'react-native';
const API_URL = 'http://your-backend-endpoint.com';
class App extends Componenenter code heret {
constructor(props) {`enter code here`
super(props);
this.state = {
data: {},
};
}
handlePress = () => {
fetch(API_URL + '/get', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: 'item name',
description: 'item description',
}),
})
.then(response => response.json())
.then(responseJson => {
console.log(responseJson);
this.setState({
data: responseJson,
});
})
.catch(error => {
console.error(error);
});
};
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={this.handlePress} style={styles.button}>
<Text style={styles.buttonText}>Send Data</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = {
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
button: {
backgroundColor: '#ddd',
padding: 10,
borderRadius: 5,
},
buttonText: {
fontSize: 18,
color: 'black',
},
};
export default App;
这是这个问题的解决方案。我已经尝试过以前的解决方案,但任何解决方案都不起作用。我尝试修复它并得到了解决方案:
(1) 首先将你的json数据转换为json字符串。
let jsonString = JSON.stringify(jsonFilePath);
(2) 然后,将 json 字符串转换为 Data。
let jsonData = JSON.parse(jsonString);
这是我的代码中的差异。
之前:
let jsonData = await fetch(jsonFilePath).then((response) => {
return response.json();
});
之后:
let jsonString = JSON.stringify(jsonFilePath);
let jsonData = JSON.parse(jsonString);
看来你的问题出在Api端。 api 返回 HTML/无内容或其未到达端点。 记录响应,以便您可以看到出了什么问题。请参阅此
我通过从我的包 json 中删除 proxy: "url" 解决了这个问题。