fix(nuxt): allow `abortMiddleware` to receive a nuxt error or error options (#7335)

This commit is contained in:
Daniel Roe 2022-09-08 09:52:00 +01:00 committed by GitHub
parent 849b8cb702
commit 9c3bef4a01
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 19 additions and 3 deletions

View File

@ -2,7 +2,7 @@ import { getCurrentInstance, inject } from 'vue'
import type { Router, RouteLocationNormalizedLoaded, NavigationGuard, RouteLocationNormalized, RouteLocationRaw, NavigationFailure, RouteLocationPathRaw } from 'vue-router'
import { sendRedirect } from 'h3'
import { hasProtocol, joinURL, parseURL } from 'ufo'
import { useNuxtApp, useRuntimeConfig, useState } from '#app'
import { useNuxtApp, useRuntimeConfig, useState, createError, NuxtError } from '#app'
export const useRouter = () => {
return useNuxtApp()?.$router as Router
@ -105,12 +105,12 @@ export const navigateTo = (to: RouteLocationRaw | undefined | null, options?: Na
}
/** This will abort navigation within a Nuxt route middleware handler. */
export const abortNavigation = (err?: Error | string) => {
export const abortNavigation = (err?: string | Partial<NuxtError>) => {
if (process.dev && !isProcessingMiddleware()) {
throw new Error('abortNavigation() is only usable inside a route middleware handler.')
}
if (err) {
throw err instanceof Error ? err : new Error(err)
throw createError(err)
}
return false
}

View File

@ -236,6 +236,15 @@ describe('middlewares', () => {
expect(html).toContain('Hello Nuxt 3!')
})
it('should allow aborting navigation on server-side', async () => {
const res = await fetch('/?abort', {
headers: {
accept: 'application/json'
}
})
expect(res.status).toEqual(401)
})
it('should inject auth', async () => {
const html = await $fetch('/auth')

View File

@ -0,0 +1,7 @@
export default defineNuxtRouteMiddleware((to) => {
if ('abort' in to.query) {
return abortNavigation({
statusCode: 401
})
}
})