问题描述
我在Axios上使用VueJ(和Vuex)与Express Api进行通信.我可以删除自己的使用服务的用户帐户
I use VueJs (and Vuex) with Axios to communicate with an Express Api. I can delete my own user account consuming a service
import api from '@/services/api.js';
export default {
deleteAccount: () => api().delete('/users')
};
其中 api
是 axios
实例.我不需要传递用户ID,因为api通过令牌识别用户.
where api
is the axios
instance. I don't need to pass in a user ID because the api identifies the user by the token.
在我的设置视图中,我可以使用此服务
Within my settings view I can consume this service
<script>
import { mapActions } from 'vuex';
import UserService from '@/services/users';
export default {
name: 'Settings',
methods: {
...mapActions('alert', [
'showSuccessAlert',
'showErrorAlert'
])
deleteAccount: async function() {
try {
await UserService.deleteAccount();
this.showSuccessAlert({ message: 'Account was deleted successfully' });
// other stuff
} catch (error) {
this.showErrorAlert({ message: error.message });
}
}
}
};
</script>
调用 UserService.deleteAccount()
会返回未完成的承诺.使用 await
返回api响应.
Calling UserService.deleteAccount()
returns me a pending promise. Using await
returns me the api response.
目前,出于测试目的,该api始终返回 500
.我认为,如果Promise被拒绝,代码将始终直接跳转到catch块中.在这里,代码返回被拒绝的Promise(并向控制台写入内部服务器错误",但传递并显示成功警报/从不执行catch块中的代码.
Currently the api always returns a 500
for testing purposes. I thought, that if the Promise gets rejected the code will always jump directly into the catch block. Here, the code returns a rejected Promise (and writes a "Internal Server Error" to the console but passes and shows a success alert / never executes the code from the catch block.
代码有什么问题?我误会了诺言吗?
What is wrong with the code? Did I misunderstand promises?
更新
我的axios实例
import axios from 'axios';
import TokensService from '@/services/tokens.js';
import store from '@/store/store.js';
function getTokenString() {
return `Bearer ${TokensService.getToken()}`;
}
export default () => {
const instance = axios.create({
baseURL: 'http://localhost:3000/',
headers: {
'Content-Type': 'application/json',
Authorization: getTokenString(),
},
});
instance.interceptors.request.use((config) => {
config.headers.Authorization = getTokenString();
return config;
}, (err) => Promise.reject(err));
instance.interceptors.response.use((res) => res, (err) => {
if (err.response.status === 401) {
store.dispatch('authentication/destroySession');
store.dispatch('alert/showErrorAlert', { message: err.message });
}
return err;
});
return instance;
};
调用 api().delete()
与 axios.delete('http://localhost:3000/users')
推荐答案
尝试在此处返回被拒绝的承诺
try returning a rejected promise here
instance.interceptors.response.use((res) => res, (err) => {
if (err.response.status === 401) {
store.dispatch('authentication/destroySession');
store.dispatch('alert/showErrorAlert', { message: err.message });
}
return Promise.reject(err);
});
根据示例 https://github.com/axios/axios#interceptors
这篇关于拒绝的HTTP承诺不会达到catch块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!