Javascript 如何实施";“之前”;axios中的回调
我正在Javascript 如何实施";“之前”;axios中的回调,javascript,vuejs2,axios,Javascript,Vuejs2,Axios,我正在Vue.js(使用axios)中编写一个具有文件上传功能的项目 在axios中发送POST请求之前,我需要执行一个操作: axios.post('/upload', form, { before: (xhr) => { fileObject.xhr = xhr; }, onUploadProgress: (e) => { //emit progress event etc... console.log('upload progress: '
Vue.js
(使用axios
)中编写一个具有文件上传功能的项目
在axios
中发送POST
请求之前,我需要执行一个操作:
axios.post('/upload', form, {
before: (xhr) => {
fileObject.xhr = xhr;
},
onUploadProgress: (e) => {
//emit progress event etc...
console.log('upload progress: ' + e.loaded);
}
}).then((response) => {
console.log('finished...');
//emit finished event etc...
}, () => {
console.log('error...');
//emit failed event etc...
});
当然,除了before
回调之外,一切都正常,因为它不是axios
选项。从文档中,我知道应该在发送请求之前使用拦截器来实现钩子。但我绕不开它
编辑:
我想要一些类似Vue的$http
:
this.$http.post('/upload', form, {
before: (xhr) => {
fileObject.xhr = xhr;
//maybe do something else here
},
progress: (e) => {
eventHub.$emit('progress', fileObject, e);
}
}).then((response) => {
eventHub.$emit('finished', fileObject);
}, () => {
eventHub.$emit('failed', fileObject);
})
如果需要在每次axios请求之前调用函数,则应使用 就你而言:
axios.interceptors.request.use((config) => {
fileObject.xhr = config;
return config;
});
axios.post('/upload', form, { ... });
为什么不先发出
xhr
请求,然后在请求完成时发送axios
post请求(在xhr
回调或then
阻塞中)?如果我想在post操作之前做其他事情(不一定是xhr的事情),该怎么办?我想把一切都放在一个地方。我想用Vue的$http:this.$http.post('/upload',form,{before:(xhr)=>{fileObject.xhr=xhr},progress:(e)=>{eventHub.$emit('progress',fileObject,e)})。然后((response)=>{eventHub.$emit.)('finished',fileObject)},()=>{eventHub.$emit('failed',fileObject)})好吧,你仍然可以把它们放在一个地方,但是按顺序执行异步请求,而不是将它们相互混合。这只是我的观点,如果出于某种原因需要你的方法,请继续寻找。你是否尝试在axios中使用transformRequest参数?我应用了它。但运行此函数需要多次