【发布时间】:2021-04-27 12:43:23
【问题描述】:
我正在制作一个多重上传文件表单。
用户取消后,一旦使用 cancel() 取消相应的 axios 调用,我就会出现奇怪的行为。我的 axios 调用被捕获在 then() 中,而它应该被捕获在 catch() 中。 then() 内部的响应返回undefined。
我很难确定我是否在前端部分做错了什么,我认为我的调用可能缺少一些标头,或者它可能在后端部分?
const payload = { file, objectId: articleId, contentType: 'article' };
const source = axios.CancelToken.source();
// callback to execute at progression
const onUploadProgress = (event) => {
const percentage = Math.round((100 * event.loaded) / event.total);
this.handleFileUploadProgression(file, {
percentage,
status: 'pending',
cancelSource: source,
});
};
attachmentService
.create(payload, { onUploadProgress, cancelToken: source.token })
.then((response) => {
// cancelation response ends up here with a `undefined` response content
})
.catch((error) => {
console.log(error);
// canceled request do not reads as errors down here
if (axios.isCancel(error)) {
console.log('axios request cancelled', error);
}
});
服务本身定义如下
export const attachmentService = {
create(payload, requestOptions) {
// FormData cannot be decamelized inside an interceptor so it's done before, here.
const formData = new FormData();
Object.entries(payload).forEach(([key, value]) =>
formData.append(decamelize(key), value),
);
return api
.post(resource, formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
...requestOptions,
})
.then((response) => {
console.log(response, 'cancelled request answered here as `undefined`');
return response.data;
})
.catch((error) => {
// not caught here (earlier)
return error.data;
});
},
};
在文件对象执行时调用取消
file.cancelSource.cancel('Request was cancelled by the user');
【问题讨论】:
-
为什么会报错?这是取消,不是错误。我不明白为什么应该将其作为错误捕获。
-
请您发布应该取消此请求的代码(根据github.com/axios/axios#cancellation 对
source变量的实际方法调用) -
@JeremyThille 这应该是一个错误,它在 axios 文档中的 catch() 中被捕获。
-
@MatthewSpence 在下面添加了电话!
-
您要么在正确调试此处已取消的请求回答和未在此处捕获的地方遇到问题,要么在之前的某个地方被捕获,包括拦截器。您没有显示
api是什么。无论如何,Axios 中的取消会导致拒绝并触发catch。如果这对您来说不同,那么问题是特定于您的情况,这意味着您有意或无意地发现了取消错误。请提供可以重现问题的stackoverflow.com/help/mcve。
标签: vue.js file-upload django-rest-framework axios request-cancelling