VueJS 上的异步中间件或捕获路由器错误的方法
Async Middleware on VueJS or a way to catch error in router
这是我在 Stack Overflow 上的第一个问题。
我在前端使用 VueJS,在后端使用 Laravel。我的问题是我必须从我的后端 API 加载我的用户将编辑的模型。但是该模型有政策,所以如果不允许用户,我的 API 可以响应 403 错误。完美!
但是在 VueJS 中如何处理呢?这是我的路由器:
{ path: '/article/:id(\d+)/edit', component: page('article/edit/index.vue') }
如果我做一个中间件,我会有异步响应,行吗?如果用户有权访问数据,我可以将其传递到我的商店吗?它看起来不是最干净的方法...
我更喜欢这样做:
在我的页面组件上,当我调用 API 时,如果响应是 403,我想抛出一个错误。但是我在哪里可以在我的路由配置中捕获该错误以使用闪现消息自动重定向?
有更好的方法吗?
谢谢!!
我认为这是最好的方法,
1 首先检查路由器参数是否为实数
2 调用 api 并得到结果,如果你得到一些错误,你会显示一个对话框或其他东西
<script>
export default {
beforeRouteEnter(to, from, next) {
//check param is a real number
if (!isNaN(to.params.id)) {
next();
}
else {
next(false); //or show message error (maybe redirect to a /error)
}
},
mounted(){
axios
.get('yoursite.com').then((response) => this.response = response)
.catch((error) => {
//show error or redirect to (/error or /logout)
})
}
}
</script>
您使用什么与 Laravel api 互动?公理?
如果您使用的是 axios,我建议您研究 Axios interceptors。它们让您可以在 返回到您的 Vuex 操作(或任何被调用的地方)之前捕获有关您的请求/响应的任何信息。因此,当您设置 Axios 实例时,您需要执行类似于以下代码片段的操作:
import axios from 'axios';
import router from '../router';
axios.interceptors.response.use(
response => {
return Promise.resolve(response);
},
error => {
const { status, data } = error.response;
if (status === 404 || status === 403) {
router.push("/not-found");
}
return Promise.reject(error);
}
);
该代码正在做的是侦听来自 Axios 的错误(如果收到 4xx 或 5xx 响应,您的后端将产生 axios 错误)然后检查从您的 API 返回的状态代码,如果它检测到 404(未找到)或 403(禁止),它会将用户重定向到未找到的页面。这当然可以定制。
这是我在 Stack Overflow 上的第一个问题。
我在前端使用 VueJS,在后端使用 Laravel。我的问题是我必须从我的后端 API 加载我的用户将编辑的模型。但是该模型有政策,所以如果不允许用户,我的 API 可以响应 403 错误。完美!
但是在 VueJS 中如何处理呢?这是我的路由器:
{ path: '/article/:id(\d+)/edit', component: page('article/edit/index.vue') }
如果我做一个中间件,我会有异步响应,行吗?如果用户有权访问数据,我可以将其传递到我的商店吗?它看起来不是最干净的方法...
我更喜欢这样做: 在我的页面组件上,当我调用 API 时,如果响应是 403,我想抛出一个错误。但是我在哪里可以在我的路由配置中捕获该错误以使用闪现消息自动重定向?
有更好的方法吗?
谢谢!!
我认为这是最好的方法,
1 首先检查路由器参数是否为实数 2 调用 api 并得到结果,如果你得到一些错误,你会显示一个对话框或其他东西
<script>
export default {
beforeRouteEnter(to, from, next) {
//check param is a real number
if (!isNaN(to.params.id)) {
next();
}
else {
next(false); //or show message error (maybe redirect to a /error)
}
},
mounted(){
axios
.get('yoursite.com').then((response) => this.response = response)
.catch((error) => {
//show error or redirect to (/error or /logout)
})
}
}
</script>
您使用什么与 Laravel api 互动?公理?
如果您使用的是 axios,我建议您研究 Axios interceptors。它们让您可以在 返回到您的 Vuex 操作(或任何被调用的地方)之前捕获有关您的请求/响应的任何信息。因此,当您设置 Axios 实例时,您需要执行类似于以下代码片段的操作:
import axios from 'axios';
import router from '../router';
axios.interceptors.response.use(
response => {
return Promise.resolve(response);
},
error => {
const { status, data } = error.response;
if (status === 404 || status === 403) {
router.push("/not-found");
}
return Promise.reject(error);
}
);
该代码正在做的是侦听来自 Axios 的错误(如果收到 4xx 或 5xx 响应,您的后端将产生 axios 错误)然后检查从您的 API 返回的状态代码,如果它检测到 404(未找到)或 403(禁止),它会将用户重定向到未找到的页面。这当然可以定制。