[英]how to disable middleware in specific page, nuxt middleware
// in nuxt.config.js =>
router: {
middleware: ['role']
},
// in middleware/role.js =>
export default function ({app}) {
if (!window.localStorage.getItem('auth.token')) {
//app.router.push('/auth/login');
console.log('middleware');
}
}
// in login.vue =>
export default {
role: false,
}
// in root page =>
export default {
role: false,
middleware({app}){
if (!window.localStorage.getItem('auth.token')) {
app.router.push('/auth/login');
}
},
}
當令牌為空並重定向用戶時,頁面會一次又一次地加載,所以我評論這個重定向並控制台記錄一條消息,以檢查發生了什么。 此角色中間件正在加載到角色中間件設置為 false 的頁面上。 檢查下面的圖像。
在這里您可以看到中間件打印了兩次,一個用於 root('/'),另一個用於登錄頁面(這里我禁用了角色中間件)。 如何禁用此中間件到此登錄頁面。
你可以用這個
middleware({ route }) {
if (!['do-not-run-here', 'public-page', 'index'].includes(route.name)) return
// all your cool code here
console.log('passed')
},
如果這是您不想擁有中間件的頁面,您可以快速返回。 在我的示例中,我們確實檢查了路由的名稱,如果它是do-no-run-here
、 public-page
或index
,則中間件根本不會在那里執行。
當然,如果你想確定頁面的名稱,設置一個name
屬性是很好的。
在所有其他的中間件上,中間件將運行得非常好。 沒有middleware: false
。
另一種解決方案是對某些頁面使用特定的layout
,並在其上使用中間件。 不要將這個用於您不想使用中間件的頁面。
謝謝 Sourav 和 Kissu,這個線程幫助我在 Nuxt 3 項目中完成了類似的事情。 我使用了您想法的變體來排除服務器中間件上的路由。
願它幫助一個未來的冒險者找到通往這個地方的路
// ~/server/middleware/auth.ts
import type { IncomingMessage, ServerResponse } from "http";
// other imports
export default async (req: IncomingMessage, res: ServerResponse) => {
const reqUrl = req.url;
/**
* Public Endpoints
*
* /api/ routes explicitly excluded from this auth middleware
*/
if (req.url.includes("api/example")) return;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.