我试图为api请求编写一个axios服务,并且我在理解这个错误时遇到了问题:
类型' AxiosResponse‘缺少’User[]‘中的以下属性: length、pop、push、const和26 more.ts(2740) const response: AxiosResponse
我的代码是这样的:
import axios from 'axios';
import User from 'src/models/User';
const http = axios.create({
baseURL: process.env.API,
headers: { 'Content-Type': 'application/json' },
});
export async function getAllUsers(): Promise<User[]> {
const response = await http.get<User[]>('users/');
return response;
}
export async function getSingleUser(itemId: string): Promise<User> {
const response = await http.get<User>(`/${itemId}`);
return response;
}
当然,我不会理解一些基本的打字概念。你能帮我吗?
如果响应将被包装在'data‘poperty中,该如何完成?
发布于 2021-07-12 12:03:23
您所缺少的事实是axios函数(如get
)返回一个AxiosInstance
,而不是您期望的实际对象。您应该访问AxiosInstance
的AxiosInstance
属性以获得所期望的值:
export async function getAllUsers(): Promise<User[]> {
const response = await http.get<User[]>('users/');
return response.data;
}
发布于 2021-07-12 12:02:35
您应该返回res.data
for http.get()
方法,请参阅响应模式
import axios from 'axios';
interface User {}
const http = axios.create({
baseURL: process.env.API,
headers: { 'Content-Type': 'application/json' },
});
export async function getAllUsers(): Promise<User[]> {
const response = await http.get<User[]>('users/').then(res => res.data)
return response;
}
export async function getSingleUser(itemId: string): Promise<User> {
const response = await http.get<User>(`/${itemId}`);
return response;
}
https://stackoverflow.com/questions/68345994
复制相似问题