使用 axios 时可能出现未处理的承诺拒绝、网络错误

Bie*_*rba 7 javascript reactjs react-native axios expo

我正在尝试使用react-native、axios 和 Expo 发送 JSON 数据,但是当我在应用程序上按“发送”时,我收到此警告:

可能未处理的承诺拒绝,错误:网络错误

当我尝试通过 POSTman 发送通知(JSON)时,我的 API 正确接收通知(JSON),但是当我尝试使用 axios 发送通知时,我收到上述警告消息,所以 React 可能没有正确发送数据。

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>
    )
}
Run Code Online (Sandbox Code Playgroud)

}

编辑

我添加了 catch() 函数,但现在错误仅出现Network Error在控制台中。

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));

}
Run Code Online (Sandbox Code Playgroud)

小智 1

使用 catch 而不是 then 进行错误处理。

.catch(error => console.log(error));
Run Code Online (Sandbox Code Playgroud)