mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-25 15:15:19 +00:00
fix(nuxt): allow abortMiddleware
to receive a nuxt error or error options (#7335)
This commit is contained in:
parent
849b8cb702
commit
9c3bef4a01
@ -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
|
||||
}
|
||||
|
@ -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')
|
||||
|
||||
|
7
test/fixtures/basic/middleware/abort.global.ts
vendored
Normal file
7
test/fixtures/basic/middleware/abort.global.ts
vendored
Normal file
@ -0,0 +1,7 @@
|
||||
export default defineNuxtRouteMiddleware((to) => {
|
||||
if ('abort' in to.query) {
|
||||
return abortNavigation({
|
||||
statusCode: 401
|
||||
})
|
||||
}
|
||||
})
|
Loading…
Reference in New Issue
Block a user