承诺拒绝(网络错误)

时间:2016-10-11 23:23:24

标签: android reactjs react-native

我正在使用axios来获取基本的JSON数据,但继续收到此错误:

Possible unhandled promise rejection (id: 0): Network Error

现在,因为错误本身不是"同样多的"有用的是知道发生了什么我改变了我的代码块并使用了.catch

错误:

Error: Network Error
    at createError (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:82235:11)
    at XMLHttpRequest.handleError (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:82107:8)
    at XMLHttpRequest.dispatchEvent (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:10284:15)
    at XMLHttpRequest.setReadyState (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:25988:6)
    at XMLHttpRequest.__didCompleteResponse (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:25836:6)
    at http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:25930:52
    at RCTDeviceEventEmitter.emit (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:9523:23)
    at MessageQueue.__callFunction (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:7339:34)
    at http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:7216:8
    at guard (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:7155:1)

代码:

componentWillMount() {
    axios.get('http://rallycoding.herokuapp.com/api/music_albums')
        .then((response) => {
            if(!response.ok){
                console.log(response.statusText);
            }
            console.log((response))
        }).then((response) => {
            console.log("ok")
        }).catch((err) => console.log(err))
}

提前致谢。

2 个答案:

答案 0 :(得分:0)

您需要在第一个语句中返回响应,否则链接将无效。

componentWillMount() {
    axios.get('http://rallycoding.herokuapp.com/api/music_albums')
        .then((response) => {
            if(!response.ok){
                console.log(response.statusText);
            }
            console.log((response))
            
            // return response
            return response;
        }).then((response) => {
            console.log("ok")
        }).catch((err) => console.log(err))
}

希望这有帮助。

答案 1 :(得分:0)

如果有其他人遇到此问题,我设法通过在Promise链末尾添加.done();来解决此问题。

componentDidMount() {
    axios.get('https://rallycoding.herokuapp.com/api/music_albums')
    .then((response) => console.log(response))
    .done();
}