Unable to catch and log the Error response from an axios request
我的react应用程序中有一个axios请求,我正在关注axios npm文档。
这是我的axios请求
1 2 3 4 5 6 7 8 9 | axios.post(helper.getLoginApi(), data) .then((response) => { console.log(response); this.props.history.push(from.pathname) }) .catch((error)=> { console.log(error); }) |
我能够成功请求成功记录数据。但是,当我有意产生一个错误并尝试进行console.log记录时,却没有记录结果,我只是看到了
POST http://localhost:3000/login 401 (Unauthorized)
:3000/login:1
Error: Request failed with status code 401
login.js:66at createError (createError.js:16)
at settle (settle.js:18)
at XMLHttpRequest.handleLoad (xhr.js:77)
但是,当我在Chrome控制台中转到"网络"标签时,可以看到以下响应。
感谢您的帮助。
来自Github文档。 axios请求的响应类似于
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | { // `data` is the response that was provided by the server data: {}, // `status` is the HTTP status code from the server response status: 200, // `statusText` is the HTTP status message from the server response statusText: 'OK', // `headers` the headers that the server responded with // All header names are lower cased headers: {}, // `config` is the config that was provided to `axios` for the request config: {}, // `request` is the request that generated this response // It is the last ClientRequest instance in node.js (in redirects) // and an XMLHttpRequest instance the browser request: {} } |
所以实际上
,因此您可以登录
When you log
console.log(error) , what you see is thestring
returned by thetoString method on theerror object.
根据同一文档的错误处理部分,您可以像
那样捕获错误响应
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | axios.post(helper.getLoginApi(), data) .then((response) => { console.log(response); this.props.history.push(from.pathname) }) .catch((error)=> { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { // The request was made but no response was received // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } }) |