Axios interceptor to retry sending FormData(Axios拦截器重试发送FormData)
本文介绍了Axios拦截器重试发送FormData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试为包含FormDataAS数据的请求创建";retry";功能。
重试发生在JWT令牌过期时,我的第二个请求(重试请求)不包含任何数据。
创意:
const axiosInstance = axios.create();
/**
* Before each request, we'll add a possible retry if the
* request need a refreshed token
*/
axiosInstance.interceptors.request.use((request) => {
if (typeof _.get(request, ['retried']) === 'undefined') {
request.retried = false;
}
return request;
});
/**
* After a request with an error, we'll check if the error is a token not refreshed.
* If we didn't already tried to refresh, we'll just fallback to the errorHandler function
*/
axiosInstance.interceptors.response.use(null, async (error) => {
const statusCode = _.get(error, ['response', 'data', 'statusCode']);
const message = _.get(error, ['response', 'data', 'message']);
const { config: request = {} } = error;
if (statusCode === 401 && !request.retried) {
try {
const newTokens = await refreshTokens();
request.retried = true;
_.set(request, ['headers', 'authorization'], newTokens.accessToken);
return axiosInstance.request(request);
} catch (e) {
return error;
}
}
return error;
});
请求:
const formData = new FormData();
formData.append('name', name);
formData.append('file', fs.createReadStream(file.path));
axiosInstance.post(
'http://localhost/upload',
formData,
{
headers: {
...formData.getHeaders(),
authorization: tokens.accessToken
}
}
);
如果我的令牌过期,请求将失败,然后拦截器将刷新我的令牌,并仅使用新的标头Authorization重试完全相同的请求。但是,在服务器端,收到的有效负载始终为空。
推荐答案
据我所知,FormData需要在重试时重新添加(我认为这是因为数据是以流的形式添加的,在请求过程中被消费了,所以新的重试不能消费已经消费的流)。
您可以查看request.data,了解我的意思。
这篇关于Axios拦截器重试发送FormData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:Axios拦截器重试发送FormData
基础教程推荐
猜你喜欢
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
