feat(nuxt): add setResponseStatus utility (#6306)

This commit is contained in:
Daniel Roe 2022-08-02 17:01:59 +01:00 committed by GitHub
parent 2cdaf8065c
commit 4379e9d922
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 31 additions and 1 deletions

View File

@ -0,0 +1,19 @@
# `setResponseStatus`
Nuxt provides composables and utilities for first-class server-side-rendering support.
You can use `setResponseStatus` to set the statusCode (and optionally the statusMessage) of the response.
`setResponseStatus` can only be called within component setup functions, plugins, and route middleware.
```js
// Set the status code to 404 for a custom 404 page
setResponseStatus(404)
// Set the status message as well
setResponseStatus(404, 'Page Not Found')
```
::alert{icon=👉}
In the browser, `setResponseStatus` will have no effect.
::

View File

@ -9,6 +9,6 @@ export { useFetch, useLazyFetch } from './fetch'
export type { FetchResult, UseFetchOptions } from './fetch' export type { FetchResult, UseFetchOptions } from './fetch'
export { useCookie } from './cookie' export { useCookie } from './cookie'
export type { CookieOptions, CookieRef } from './cookie' export type { CookieOptions, CookieRef } from './cookie'
export { useRequestHeaders, useRequestEvent } from './ssr' export { useRequestHeaders, useRequestEvent, setResponseStatus } from './ssr'
export { abortNavigation, addRouteMiddleware, defineNuxtRouteMiddleware, navigateTo, useRoute, useActiveRoute, useRouter } from './router' export { abortNavigation, addRouteMiddleware, defineNuxtRouteMiddleware, navigateTo, useRoute, useActiveRoute, useRouter } from './router'
export type { AddRouteMiddlewareOptions, RouteMiddleware } from './router' export type { AddRouteMiddlewareOptions, RouteMiddleware } from './router'

View File

@ -15,3 +15,13 @@ export function useRequestHeaders (include?) {
export function useRequestEvent (nuxtApp: NuxtApp = useNuxtApp()): CompatibilityEvent { export function useRequestEvent (nuxtApp: NuxtApp = useNuxtApp()): CompatibilityEvent {
return nuxtApp.ssrContext?.event as CompatibilityEvent return nuxtApp.ssrContext?.event as CompatibilityEvent
} }
export function setResponseStatus (code: number, message?: string) {
const event = process.server && useRequestEvent()
if (event) {
event.res.statusCode = code
if (message) {
event.res.statusMessage = message
}
}
}

View File

@ -35,6 +35,7 @@ export const appPreset = defineUnimportPreset({
'useCookie', 'useCookie',
'useRequestHeaders', 'useRequestHeaders',
'useRequestEvent', 'useRequestEvent',
'setResponseStatus',
'useRouter', 'useRouter',
'useRoute', 'useRoute',
'useActiveRoute', 'useActiveRoute',