【发布时间】:2018-07-22 10:42:05
【问题描述】:
我正在尝试使用 axios 调用 API 并返回数据。
我有以下代码可以正常工作
axios.get('http://api/courses')
.catch(function (error) {
if (error.response) {
console.log(error.response.status);
} else {
console.log('Error', error.message);
}
})
.then(response => {
console.log(response.data)
});
这很好用,API 返回 200 和数据,所以在控制台中我得到了返回的数据。
但这不起作用
axios.get('http://api/courses')
.catch(function (error) {
if (error.response) {
console.log(error.response.status);
} else {
console.log('Error', error.message);
}
})
.then(response => {
console.log(response.data)
});
在上述调用中,我从 API 返回一个 401,我希望能够检测到它并做一些事情(我目前正在做一个 console.log)。但是在控制台中我收到以下错误:
GET http://api/courses 401 (Unauthorized)
(anonymous) @ spread.js:25
e.exports @ spread.js:25
e.exports @ spread.js:25
Promise.then (async)
r.request @ spread.js:25
r.(anonymous function) @ spread.js:25
(anonymous) @ index.js:20
(anonymous) @ (index):49
(index):58 Uncaught (in promise) TypeError: Cannot read property 'data' of undefined
at axios.get.catch.then.response ((index):58)
at <anonymous>
有没有办法捕获 401?这似乎是需要身份验证的 API 的常见做法,但我似乎无法解决。 谢谢
【问题讨论】:
标签: javascript axios