拦截器
你可以在请求或响应被 then
或 catch
处理之前拦截它们。
¥You can intercept requests or responses before they are handled by then
or catch
.
use
函数将一个处理程序添加到处理程序列表中,该处理程序将在 Promise 完成或拒绝时运行。处理程序由 fulfilled 和 rejected 函数定义。
¥The use
function adds a handler to the list of handlers to be run when the Promise is fulfilled or rejected. The handler is defined by the fulfilled and rejected functions.
有一个可选的 options
对象可以作为第三个参数传入。如果同步选项为 true,则使用 synchronous
。如果同步选项为 false,则该处理程序定义为异步的。如果未提供同步选项,则处理程序将被定义为异步。runWhen
将控制提供的拦截器何时运行。提供一个函数,该函数将返回 true 或 false 来判断是否应该运行,默认值始终为 true。
¥There is an optional options
object that can be passed in as the third parameter. synchronous
if the synchronous option is true. The handler is defined as asynchronous if the synchronous option is false. If the synchronous option is not provided, the handler is defined as asynchronous. runWhen
will control when the provided interceptor will run. Provide a function that will return true or false on whether it should run, defaults to always true.
// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
},
{ synchronous: true, runWhen: () => /* This function returns true */}
);
// Add a response interceptor
axios.interceptors.response.use(function onFulfilled(response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
}, function onRejected(error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});
正常情况下,仅当响应类型为 2xx 时才会调用 onFulfilled
响应拦截器,否则会调用 onRejected
。但是,此行为取决于 validateStatus。例如,如果 validateStatus
设置为始终返回 true
,则所有响应都会调用 onFulfilled
。
¥In normal circumstances the onFulfilled
response interceptor is only called for responses in the 2xx range, and onRejected
is called otherwise.
However, this behavior depends on validateStatus.
For instance, if validateStatus
is setup to always return true
, then onFulfilled
will be called for all responses.
如果你之后需要删除拦截器,则可以这样。
¥If you need to remove an interceptor later you can.
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
你可以将拦截器添加到 axios 的自定义实例。
¥You can add interceptors to a custom instance of axios.
const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});