如何将响应数据包含到 axios 响应中?
Posted
技术标签:
【中文标题】如何将响应数据包含到 axios 响应中?【英文标题】:How can I include response data to axios response? 【发布时间】:2022-01-15 05:05:31 【问题描述】:我尝试使用 Axios 拦截器。我面临的问题是我无法使用 Axios 显示从 API 获得的响应,或者即使可以显示,它也会显示恒定数据。
axios.defaults.baseURL = 'https://localhost:5001/api/';
axios.defaults.withCredentials = true;
const responseBody = res => res.data;
axios.interceptors.response.use(async response =>
const pagination = response.headers["x-pagination"];
if (pagination)
const parsed = JSON.parse(pagination);
let metaData =
currentPage: parsed.currentPage,
pageSize: parsed.pageSize,
totalPages: parsed.totalPages,
totalCount: parsed.totalCount
;
response.data =
metaData,
data: response.data //I want to change this data
// For example there is an endpoint named getAll and it returns all object
// Also there is a get endpoint and it returns a single object
// But the problem is axios always return getAll endpoint's data.
;
return response;
, error =>
return Promise.reject(error);
);
这是我的请求对象
const requests =
get: (url, params) => axios.get(url, params).then(responseBody),
post: (url, data) => axios.post(url, data).then(responseBody),
put: (url, data) => axios.put(url, data).then(responseBody),
delete: (url) => axios.delete(url).then(responseBody),
postForm: (url, data) => axios.post(url, data,
headers:
'Content-Type': 'multipart/form-data'
).then(responseBody),
putForm: (url, data) => axios.put(url, data,
headers:
'Content-Type': 'multipart/form-data'
).then(responseBody)
;
这是我的 API 端点
const Endpoints =
getAll: () => requests.get('Endpoint'),
get: (id) => requests.get(`Endpoint/$id`),
create: (data) => requests.postForm('Endpoint', data),
update: (id, data) => requests.putForm(`Endpoint/$id`, data),
delete: (id) => requests.delete(`Endpoint/$id`),
我错过了什么?另外,我使用 Redux Slice。如果你愿意,我也可以发送我写的 redux 代码。
【问题讨论】:
【参考方案1】:axios.interceptors.response.use(async response =>
const pagination = response.headers["x-pagination"];
if (pagination)
const parsed = JSON.parse(pagination);
let metaData =
currentPage: parsed.currentPage,
pageSize: parsed.pageSize,
totalPages: parsed.totalPages,
totalCount: parsed.totalCount
;
response.data =
metaData,
data: response.data
;
return response;
return response; // problem solved after this
, error =>
return Promise.reject(error);
);
问题是我忘记返回响应,所以我总是得到相同的数据。
【讨论】:
以上是关于如何将响应数据包含到 axios 响应中?的主要内容,如果未能解决你的问题,请参考以下文章
我们如何从 JSON 响应中访问包含连字符的数据? [复制]
Axios 响应数据未加载到 Laravel 中的 Vue 组件上