【发布时间】:2019-08-31 23:33:30
【问题描述】:
我使用 VueJs(和 Vuex)和 Axios 来与 Express Api 通信。我可以删除自己使用服务的用户帐户
import api from '@/services/api.js';
export default {
deleteAccount: () => api().delete('/users')
};
其中api 是axios 实例。我不需要传入用户 ID,因为 api 通过 token 来识别用户。
在我的设置视图中,我可以使用此服务
<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 响应。
目前 api 总是返回 500 用于测试目的。我想,如果 Promise 被拒绝,代码总是会直接跳到 catch 块中。在这里,代码返回一个被拒绝的 Promise(并向控制台写入“内部服务器错误”,但传递并显示成功警报/从不执行 catch 块中的代码。
代码有什么问题?我误解了承诺吗?
更新
我的 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')相同
【问题讨论】:
-
returns a 500- http 状态并不一定意味着被拒绝的承诺 - 例如浏览器fetch不会拒绝 500、404 或任何成功(就获得 http 响应而言) ) 请求 -
返回状态码 500 会自动拒绝承诺吗?
-
是的,通常是这样
-
api().delete的代码是什么样的?是你的代码吗? -
据我所知,所有“失败的请求”都会跳转到 catch 块中
标签: javascript vue.js axios