我想用下面的代码在我的main.js中截获代码为!= 200的所有api响应,分派一个操作,然后显示一个显示错误消息的toast。我使用的是vue-resource,我的拦截器如下:
Vue.http.interceptors.push(function(request, next) {
next(function(response) {
debugger;
if (response.status != 200) {
store.dispatch("errorAction", response);
}
});
});但是回调中的代码永远不会被访问到...
我的api调用是这样完成的。java控制器只是抛出一个异常,错误代码为500。
Vue.http
.get(`http://${ADDRESS}/${store.state.module}/foo/exception`)
.then(() => {}, () => {});我是Promises的新手,可能会把事情搞得一团糟,但我不想给每个promise都传递一个错误回调。如果我的请求如下:
export function getFoo(cb) {
Vue.http
.get(`http://${ADDRESS}/${store.state.module}/foo`)
.then(
response => {
return response.json();
},
() => {}
)
.then(foos => {
cb(foos);
});
}我想去掉() => {},并使用拦截器代码来运行。
发布于 2019-10-02 03:45:46
我想我也遇到过同样的问题,所以我试着查看了文档。嗯,这很简单,你只需要这样做:
在main.js中
Vue.http.interceptors.push(function(req) {
//Here you can add some headers, if needed
req.headers.set('awesomeHeader', 'owwnt')
return function(res) {
if( res.status == 200 || res.status == 201 || res.status == 202 ){ //Here you add the status codes that you'll work with, just like my example
//Sucess response
} else {
//Every time witch an request return a status differ form the list above, you can do whatever you want, for example you can redirect the page for a new one
window.location.href = `http://localhost:8080/#`
//If you want to display a notification, you need to import the component before, and then do something like it:
Notification.success({
title: 'error',
message: 'Unauthorized request!',
offset: 100
})
}
};
})它回答你的问题了吗?我希望是这样。
https://stackoverflow.com/questions/58104245
复制相似问题