【发布时间】:2018-09-08 21:30:51
【问题描述】:
所以我正在尝试多种方法从我的 axios HTTP 调用中获取错误响应状态,但发生了一些奇怪的事情。
getData() {
axios.get(`/api/article/getObserved.php`, axiosConfig)
.then(response => {
console.log('success');
console.log(response);
})
.catch(err => {
console.log('error');
console.log(err.status);
console.log(err.response.status)
});
}
所以我调用了我的 getObserved 端点,虽然它返回 http_response_code(503);,但它会返回 .then() 部分,因为它控制台日志“成功”字符串。
这是控制台的输出:
GET http://localhost/obiezaca/v2/api/article/getObserved.php 503(服务不可用)
成功 favouriteArticles.vue?31bd:83
我已经完成了数百次这样的调用,并且这个.catch 总是捕获错误,即使我没有像在其他语言中那样抛出异常。不过我也试过这样:
getData() {
axios.get(`/api/article/getObserved.php`, axiosConfig)
.then(response => {
console.log('success');
console.log(response);
}, function (err) {
console.log('error');
console.log(err.status);
console.log(err.response.status);
})
.catch(err => {
console.log('error');
console.log(err.status);
console.log(err.response.status)
});
}
尽管我的端点返回了这个 503 错误请求,但它仍然没有控制台“错误”。为什么?
我还想补充一点,我认为my endpoint 工作不正常,因为我正在通过测试和手动通过 cURL 和 POSTMAN 对其进行测试,一切都很好。
编辑,因为当我没有从我的端点获取数据并且我只需要处理一个错误(是否有数据)时,响应是未定义的,所以我只是做了这样的事情:
getData() {
axios.get(`/api/article/getObserved.php`, axiosConfig)
.then(response => {
if(response) {
this.articles = response.data.records;
} else {
this.noFavourite = true;
this.articles = [];
}
});
它正在工作。我会祈祷不要在需要处理几个不同错误的调用中遇到相同的问题。
【问题讨论】:
-
你能告诉我们
axiosConfig里有什么吗? -
当然,但它只是导出baseURL
export default { baseURL: 'http://localhost/obiezaca/v2' },我在axios之后打开脚本标签后导入它:import axios from 'axios'; import axiosConfig from '../../../../../config/axios.conf.js';。 -
您可以尝试将
/api/article/getObserved.php更改为/api/article/iKnowThisWillBeA404.php之类的内容,看看是否会导致.catch触发? -
axios 不处理网络错误
-
当我将 URL 更改为不存在的 URL 时,它会正确触发
.catch和,function(err)。这是什么意思? @Abdeslem Charif 这与网络连接无关。
标签: javascript http axios