Javascript react axios然后工作,但catch不工作';行不通
我已经阅读了以下问题,但找不到解决方案Javascript react axios然后工作,但catch不工作';行不通,javascript,reactjs,react-native,axios,Javascript,Reactjs,React Native,Axios,我已经阅读了以下问题,但找不到解决方案 我想得到错误400,500。。。有人说你应该赶上,但我尝试了,什么也没发生。对于测试,我编写了一个函数来获取错误404400 export const myAxios = url => { Axios.get(url) .then(response => { // Success console.log("then response ", response); }) .catch(e
export const myAxios = url => {
Axios.get(url)
.then(response => {
// Success
console.log("then response ", response);
})
.catch(error => {
// Error
if (error.response) {
console.log("error respone", 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("erros request: ", error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log("Error message", error.message);
}
console.log("errors config : ", error.config);
});
};
axios无法捕获错误,浏览器控制台会记录以下内容:
xhr.js:172 GET http://localhost:3000/app/..../choices 404 (Not Found)
dispatchXhrRequest @ xhr.js:172
xhrAdapter @ xhr.js:11
dispatchRequest @ dispatchRequest.js:59
Promise.then (async)
request @ Axios.js:53
Axios.<computed> @ Axios.js:68
wrap @ bind.js:9
myAxios @ textaxios.js:4
(anonymous) @ List.jsx:14
commitHookEffectList @ react-dom.development.js:22030
您的代码似乎很好,也许您正试图访问的是本地端点(资源) 下面是使用示例占位符服务的示例:
document.getElementById('btn-valid')。addEventListener('click',()=>{
//有效URL
myAxios('https://jsonplaceholder.typicode.com/todos/1')
})
document.getElementById('btn-invalid')。addEventListener('click',()=>{
//无效的URL
myAxios('https://jsonplaceholder.typicode.com/todus/1')
})
const myAxios=url=>{
获取(url)
。然后(响应=>{
console.log('success',response);
})
.catch(错误=>{
console.log('error',error)
})
}
无效的URL
有效URL
您确定它没有记录此console.log(error.request)代码>?您无法知道,请尝试将一些文本添加到其他错误日志中,您必须排除这种情况。已完成,但它不是日志记录,是否与本地日志相关?我现在正在本地主机上处理我的项目。阅读时,可能是axios正在将错误解析为响应。您可以在catch中尝试console.log(“error”,error)
?另一件值得尝试的事情是使用一个拦截器,类似于VSG24提到的拦截器。除了上面提到的,您使用的是什么版本的axios?几年前,添加了validateStatus
config选项,因此如果不进行更改,它可能会将您发送到。然后对4XX响应进行回调。您的代码似乎工作正常。这是一个复制它的方法。您应该在控制台中看到错误。我看到的唯一奇怪的事情是Axios
带有大写的A。如何准确定义Axios
?
"axios": "^0.19.0"
"react": "^16.12.0"