javascript - 反应原生的pots API [object object]
问题描述
我在向服务器发送数据时遇到问题。当我尝试使用以下响应通过邮递员成功提交数据并且如果我激活“Content-Type”:“application / json”
我有一个问题是 JSON Parse 错误:无法识别的令牌 '<'
{
"status": 200,
"message": "success login",
"id_kurir": "3",
"username": "tester",
}
当我尝试使用代码时,我收到一个错误,即 [object object]
这是我的代码:
constructor(props) {
super(props);
this.state = {
Uname : '',
Upass : ''
}
}
login= ()=>{
const {Uname,Upass} = this.state;
fetch('https://example.com/login', {
method: 'POST',
// headers: {
// 'Accept' : 'application/json',
// 'Content-Type': 'application/json'
//},
body: JSON.stringify({
username: Uname,
password: Upass
})
})
.then((response) => response.json())
.then((responseJson) => {
alert(responseJson);
console.log(JSON.stringify(responseJson));
}).catch((error)=>{
console.log(error);
})
Keyboard.dismiss();
}
<Form style={styles.mainForm}>
<Item style={styles.formItems}>
<Input placeholder="Username" style={styles.Input} onChangeText={Uname => this.setState({Uname})}/>
</Item>
<Item style={styles.formItems}>
<Input style={styles.Input} secureTextEntry={true} onChangeText={(Upass) => this.setState({Upass})}/>
</Item>
<View style={styles.Button}>
{/* <Button block style={styles.mainBtn} onPress={() => this.props.navigation.navigate('home')}> */}
<Button block info style={styles.mainBtn} onPress={this.login}>
<Text style={styles.btnText}>Submit</Text>
</Button>
</View>
</Form>
错在哪里?
解决方案
服务器可能出现 404 或 500 错误。而不是 response.json() 使用 response.text() 您将获得文本中的 html。
我假设您的服务器没有采用 JSON 格式的正文
尝试使用下面的代码。
选项1:
fetch('https://example.com/login', {
method: 'POST',
body: JSON.stringify({
username: Uname,
password: Upass
})
}).then(response => response.text()).then((text) => {
if (Platform.OS === 'android') {
text = text.replace(/\r?\n/g, '').replace(/[\u0080-\uFFFF]/g, '');
// If android, remove unwanted chars.
}
return text;
}).then(response => JSON.parse(response));
选项 2:
fetch('https://example.com/login', {
method: 'POST',
body: JSON.stringify({
username: Uname,
password: Upass
})
}).then((response) => response.text()).then((responseJson) => {
alert(JSON.stringify(responseJson));
console.log(JSON.stringify(responseJson));
}).catch((error) => {
alert(JSON.stringify(error));
console.log(error);
})
推荐阅读
- angular - 如何在 Ionic Ecommerce App 中应用产品搜索
- dns - 如何强制用户从特定的办公地点到特定的 ADFS 服务器
- delphi - AdvBadgeGlowButton1 标题上的 delphi 用例
- c++ - 如何在 RPi3 上的交叉编译应用程序的 MainWindow 上显示边框和标题栏?
- php - 如何在站点子文件夹中配置 php symfony4 应用程序(路由问题)
- listview - 显示弹出菜单后 ListView HitTest 返回错误值
- mongodb - 无法在 mongodb 中搜索“一次”
- firebase - 带有firebase数据库的简单js todo应用程序
- javascript - nodejs异步/承诺地狱
- c# - 在c#中通过十进制列表过滤Linq数据表