gpt4 book ai didi

reactjs - 带有 typescript 问题的 Axios 发布请求

转载 作者:行者123 更新时间:2023-12-05 01:06:18 25 4
gpt4 key购买 nike

我正在尝试将 typescript 添加到我当前的项目中,因此在将它与 Axios 发布请求一起使用后,我遇到了一个问题。

用例是我想在我的帖子请求中发送“电子邮件”“名字”“姓氏”和“密码”,作为回应我想要“accessToken”

下面是代码

export interface UserRegistrationModel {
email: string;
password: string;
firstname: string;
lastname: string;
}



export const register = async (user: UserRegistrationModel) => {
const { data } = await http.post<UserRegistrationModel>("/users", user);
return data;
};

这是我提交注册表后调用的函数

register(values)
.then((data) => {
console.log(data.accessToken);
setLoading(false);

})
.catch(() => {
setLoading(false);

});

所以当我尝试通过 data.acessToken 访问“accessToken”时,在我的 then block 中抛出错误

Property 'accessToken' does not exist on type 'UserRegistrationModel

所以我尝试定义一个名为“AuthModel”的新接口(interface),但是当我将它分配给像这样的数据时

export interface AuthModel {
accessToken: string
}


register(values)
.then((data:AuthModel) => {
console.log(data.accessToken);
setLoading(false);
})
.catch(() => {
setLoading(false);
setSubmitting(false);
setStatus("Registration process has broken");
});

它说

Argument of type '(data: AuthModel) => void' is not assignable toparameter of type '(value: UserRegistrationModel) => void |PromiseLike'. Types of parameters 'data' and 'value' areincompatible.Property 'accessToken' is missing in type 'UserRegistrationModel' but required in type 'AuthModel'.

下面是任何人都想看的 axios 配置

//http.ts

import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";

enum StatusCode {
Unauthorized = 401,
Forbidden = 403,
TooManyRequests = 429,
InternalServerError = 500,
}

const headers: Readonly<Record<string, string | boolean>> = {
Accept: "application/json",
"Content-Type": "application/json; charset=utf-8",
"Access-Control-Allow-Credentials": true,
"X-Requested-With": "XMLHttpRequest",
};

// We can use the following function to inject the JWT token through an interceptor
// We get the `accessToken` from the localStorage that we set when we authenticate
const injectToken = (config: AxiosRequestConfig): AxiosRequestConfig => {
try {
const token = localStorage.getItem("accessToken");

if (token != null) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
} catch (error: any) {
throw new Error(error);
}
};

class Http {
private instance: AxiosInstance | null = null;

private get http(): AxiosInstance {
return this.instance != null ? this.instance : this.initHttp();
}

initHttp() {
const http = axios.create({
baseURL: "https://api.example.com",
headers,
withCredentials: true,
});

http.interceptors.request.use(injectToken, (error) =>
Promise.reject(error)
);

http.interceptors.response.use(
(response) => response,
(error) => {
const { response } = error;
return this.handleError(response);
}
);

this.instance = http;
return http;
}

request<T = any, R = AxiosResponse<T>>(
config: AxiosRequestConfig
): Promise<R> {
return this.http.request(config);
}

get<T = any, R = AxiosResponse<T>>(
url: string,
config?: AxiosRequestConfig
): Promise<R> {
return this.http.get<T, R>(url, config);
}

post<T = any, R = AxiosResponse<T>>(
url: string,
data?: T,
config?: AxiosRequestConfig
): Promise<R> {
return this.http.post<T, R>(url, data, config);
}

put<T = any, R = AxiosResponse<T>>(
url: string,
data?: T,
config?: AxiosRequestConfig
): Promise<R> {
return this.http.put<T, R>(url, data, config);
}

delete<T = any, R = AxiosResponse<T>>(
url: string,
config?: AxiosRequestConfig
): Promise<R> {
return this.http.delete<T, R>(url, config);
}

// Handle global app errors
// We can handle generic app errors depending on the status code
private handleError(error: any) {
const { status } = error;

switch (status) {
case StatusCode.InternalServerError: {
// Handle InternalServerError
break;
}
case StatusCode.Forbidden: {
// Handle Forbidden
break;
}
case StatusCode.Unauthorized: {
// Handle Unauthorized
break;
}
case StatusCode.TooManyRequests: {
// Handle TooManyRequests
break;
}
}

return Promise.reject(error);
}
}

export const http = new Http();

最佳答案

可以设置不同的类型来输入输出数据(axios 定义):

post<T = never, R = AxiosResponse<T>>(url: string, data?: T, config?: AxiosRequestConfig<T>): Promise<R>;

所以,在你的情况下,它会是这样的:

export interface UserRegistrationModel {
email: string;
password: string;
firstname: string;
lastname: string;
}

export const register = async (user: UserRegistrationModel) => {
const { data } = await http.post<UserRegistrationModel, AxiosResponse<{ accessToken: string }>>("/users", user);
return data;
};

关于reactjs - 带有 typescript 问题的 Axios 发布请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69417883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com