我正在尝试使用react-native,axios和expo发送JSON,但是当我在应用程序上按“发送”时,出现以下警告:
可能未处理的承诺被拒绝,错误:网络错误
当我尝试通过Postman发送通知时,我的API正确接收了通知(JSON),但是当我尝试通过axios通过react-native发送通知时,我收到了警告消息,所以也许react未发送数据正确。
最大的问题是使用axios而不是fetch的承诺
export default class NotificationsInput extends React.Component {
state = {
token: '',
title: '',
body: ''
}
handleToken = event => {
this.setState({ token: event.target.value })
}
handleTitle = event => {
this.setState({ title: event.target.value })
}
handleBody = event => {
this.setState({ body: event.target.value })
}
handleSubmit = event => {
event.preventDefault();
let notification = JSON.stringify({
token: this.state.token,
title: this.state.title,
body: this.state.body
})
let headers = {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}
axios.post(`http://127.0.0.1:8000/send_push_message/`, notification, headers)
.then(res => {
console.log(res);
console.log(res.data)
})
.then(error => console.log(error));
}
render() {
return (
<View>
<TextInput onChange={this.handleToken}
style={{ height: 25, width: 200, borderColor: 'black', borderWidth: 1 }}
/>
<TextInput onChange={this.handleTitle}
style={{ height: 40, width: 200, borderColor: 'black', borderWidth: 1 }}
/>
<TextInput onChange={this.handleBody}
style={{ height: 40, width: 200, borderColor: 'black', borderWidth: 1 }}
/>
<Button onPress={this.handleSubmit} title="Send">Send</Button>
</View>
)
}
}
编辑我添加了catch()函数,但现在错误仅是控制台中的“网络错误”
handleSubmit = event => {
event.preventDefault();
let notification = JSON.stringify({
token: this.state.token,
title: this.state.title,
body: this.state.body
})
let headers = {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}
axios.post(`http://127.0.0.1:8000/send_push_message/`, notification, headers)
.then(res => {
console.log(res);
console.log(res.data)
})
.catch(error => console.log(error));
}
答案 0 :(得分:0)
使用catch代替错误处理。
.catch(error => console.log(error));
答案 1 :(得分:0)
我可以看到您已将两个链接在一起,然后是不正确的。您需要一个catch块来捕获网络错误。在下面看看
axios.post(`http://127.0.0.1:8000/send_push_message/`, notification, headers)
.then(res => {
console.log(res);
console.log(res.data)
})
.catch(error => console.log(error));