我有一个小项目,我使用的是没有Redux或Router的React。另外,我对每个请求都使用axios。
我需要做的是,如果任何响应都有401错误代码,则我需要显示一种带有适当错误消息的模式。
我创建了一个axios实例,并在其中设置了响应拦截器:
const axiosInstance = axios.create({
baseURL: URL_PREFIX,
headers: {
'X-Requested-With': 'XMLHttpRequest',
},
})
axiosInstance.interceptors.response.use(
response => response,
error => {
if(error.response.status === 401) {
// I want to show modal from here,
// but this is outside of my component tree
// and I can not access my modal state to set it open.
}
return error
}
)
然后,我将创建的axios实例用于每个API调用。
我还尝试从根组件useEffect()方法设置响应拦截器。但这不起作用
有没有不用Redux或Router的好方法吗?
答案 0 :(得分:0)
您可以使用axios.catch()方法:
axios.get('url')
.then(response => // response.data )
.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.status);
} 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);
}
console.log(error.config);
});
更新:
创建实例模块:
// axiosInstance.js
import axios from "axios"
const axiosInstance = axios.create({
baseURL: "url"
})
// You can do the same with `request interceptor`
axiosInstance.interceptors.response.use(
response => {
// intercept response...
return response
},
error => {
// intercept errors
return Promise.reject(error)
}
)
// You can create/export more then one
export { axiosInstance }
然后导入它到您的组件中:
import { axiosInstance } from "./axiosInstance"
const SomeComponent = () => {
// You may want to use state to store the returned values ...
useEffect(() => {
// Call the instance
axiosInstance.get().then(res => {
if (res.status === 200) {
// Everything is OK
// Else, check if the error object is exist
} else if (res.response) {
// Error object: `res.response`
// For error codes: `res.response.status`
if(res.response.status === 401) {
// Do your stuff
}
}
})
}, [])
return ( ... )
}