[英]How to use Axios interceptor with typescript correctly?
I have created an axios interceptor:我创建了一个 axios 拦截器:
instance.interceptors.response.use(async (response) => {
return response.data;
}, (err) => {
return Promise.reject(err);
});
which gets the response
and returns the data
property.它获取
response
并返回data
属性。
The response
object is of type AxiosResponse<any, any>
and the data
property is just the data of the type AxiosResponse<any, any>.data
. response
object 的类型是AxiosResponse<any, any>
并且data
属性只是AxiosResponse<any, any>.data
类型的数据。
The problem is that when I use this axios client问题是当我使用这个 axios 客户端时
const instance = axios.create({...});
// ...etc
// add interceptor
then I do:然后我做:
customAxiosClient.get().then((data: /* here data is of type AxiosResponse instead of AxiosResponse.data */)
How to solve this?如何解决这个问题?
You have to just specify the response data type in axios get method, like so:您只需在 axios get 方法中指定响应数据类型,如下所示:
axios.get<never, YourDataType>(...)
Answer by Rechu works, but I'm going to provide an alternative. Rechu 的回答有效,但我将提供一个替代方案。
You can create a reusable function in order to keep your axios
instance global.您可以创建一个可重用的 function 以使您的
axios
实例保持全局性。 I use this myself in production.我自己在生产中使用它。
First off, create a folder/file named utils/http.ts
in your project.首先,在您的项目中创建一个名为
utils/http.ts
的文件夹/文件。 Next, this is my reusable function to keep everything in one place.接下来,这是我的可重复使用的 function 以将所有内容保存在一个地方。
import axiosClient from "axios";
import type { AxiosRequestConfig } from "axios";
/**
* Creates an initial 'axios' instance with custom settings.
*/
const instance = axiosClient.create({
headers: {
Accept: "application/json",
"Content-Type": "application/json; charset=utf-8",
},
});
/**
* Handle all responses. It is possible to add handlers
* for requests, but it is omitted here for brevity.
*/
instance.interceptors.response.use(
(res) => res.data,
(err) => {
if (err.response) {
return err.response.data;
}
if (err.request) {
return err.request;
}
return err.message;
}
);
/**
* Replaces main `axios` instance with the custom-one.
*
* @param cfg - Axios configuration object.
* @returns A promise object of a response of the HTTP request with the 'data' object already
* destructured.
*/
const axios = <T>(cfg: AxiosRequestConfig) => instance.request<any, T>(cfg);
export default axios;
Finally, use it like the following code snippet:最后,像下面的代码片段一样使用它:
const login = () => {
const creds = { username: "user", password: "pass" };
axios<User>({ method: "POST", url: "/api/v1/auth/login", data: creds })
.then((user) => { /* do whatever with user here */ })
.catch((err) => { /* handle errors */);
};
It will be typed and ready for immediate usage.它将被输入并准备好立即使用。 The
any
in axios
function can be substituted with unknown
as well. axios
function 中的any
也可以用unknown
代替。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.