fix(nuxt): only redirect if path is not the same as initial url (#21815)

This commit is contained in:
Daniel Roe 2023-06-27 11:15:35 +01:00 committed by GitHub
parent d7267663f2
commit 489b088836
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 24 additions and 1 deletions

View File

@ -198,7 +198,7 @@ const plugin: Plugin<{ router: Router }> = defineNuxtPlugin({
fatal: false,
statusMessage: `Page not found: ${to.fullPath}`
})))
} else if (process.server && to.redirectedFrom) {
} else if (process.server && to.redirectedFrom && to.fullPath !== initialURL) {
await nuxtApp.runWithContext(() => navigateTo(to.fullPath || '/'))
}
})

View File

@ -117,6 +117,11 @@ describe('pages', () => {
expect(headers.get('location')).toEqual('/')
})
it('allows routes to be added dynamically', async () => {
const html = await $fetch('/add-route-test')
expect(html).toContain('Hello Nuxt 3!')
})
it('includes page metadata from pages added in pages:extend hook', async () => {
const res = await fetch('/page-extend')
expect(res.headers.get('x-extend')).toEqual('added in pages:extend')

View File

@ -0,0 +1,18 @@
export default defineNuxtPlugin((_nuxtApp) => {
const router = useRouter()
router.beforeEach((to) => {
if (to.path !== '/add-route-test') { return }
if (router.getRoutes().some(route => route.path === to.path)) {
return
}
router.addRoute({
path: to.path,
name: to.path,
component: () => import('~/pages/index.vue')
})
return to.path
})
})