docs: improve server routes guide (#4401)

This commit is contained in:
Maciej Jezierski 2022-04-22 18:11:25 +02:00 committed by Pooya Parsa
parent 46ecbc558d
commit 0eebb0a390

View File

@ -9,7 +9,7 @@ The handler can directly return JSON data, a `Promise` or use `event.res.end()`
::ReadMore{link="https://nitro.unjs.io/guide/routing.html" title="Nitro Route Handling Docs"} ::ReadMore{link="https://nitro.unjs.io/guide/routing.html" title="Nitro Route Handling Docs"}
:: ::
## Usage Example ## Example
Create a new file in `server/api/hello.ts`: Create a new file in `server/api/hello.ts`:
@ -60,7 +60,18 @@ export default defineEventHandler((event) => {
}) })
``` ```
## Matching Route Parameters ## Server Utilities
Server routes are powered by [unjs/h3](https://github.com/unjs/h3) which comes with a handy set of helpers.
::ReadMore{link="https://www.jsdocs.io/package/h3#package-index-functions" title="Available H3 Request Helpers"}
::
You can add more helpers by yourself inside the `~/server/utils` directory.
## Usage Examples
### Matching Route Parameters
Server routes can use dynamic parameters within brackets in the file name like `/api/hello/[name].ts` and accessed via `event.context.params`. Server routes can use dynamic parameters within brackets in the file name like `/api/hello/[name].ts` and accessed via `event.context.params`.
@ -72,7 +83,7 @@ export default defineEventHandler(event => `Hello, ${event.context.params.name}!
You can now universally call this API using `await $fetch('/api/hello/nuxt')` and get `Hello, nuxt!`. You can now universally call this API using `await $fetch('/api/hello/nuxt')` and get `Hello, nuxt!`.
## Matching HTTP Method ### Matching HTTP Method
Handle file names can be suffixed with `.get`, `.post`, `.put`, `.delete`, ... to match request's [HTTP Method](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods). Handle file names can be suffixed with `.get`, `.post`, `.put`, `.delete`, ... to match request's [HTTP Method](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods).
@ -90,7 +101,7 @@ Given the Example above, fetching `/test` with:
- **POST** method: Returns `Test post handler` - **POST** method: Returns `Test post handler`
- Any other method: Returns 404 error - Any other method: Returns 404 error
## Catch-all route ### Catch-all route
Catch-all routes are helpful for fallback route handling. For Example, creating a file in the `~/server/api/foo/[...].ts` will register a catch-all route for all requests that do not match any route handler, such as `/api/foo/bar/baz`. Catch-all routes are helpful for fallback route handling. For Example, creating a file in the `~/server/api/foo/[...].ts` will register a catch-all route for all requests that do not match any route handler, such as `/api/foo/bar/baz`.
@ -104,7 +115,7 @@ export default defineEventHandler(() => `Default foo handler`)
export default defineEventHandler(() => `Default api handler`) export default defineEventHandler(() => `Default api handler`)
``` ```
## Handling Requests with Body ### Handling Requests with Body
```ts [/server/api/submit.post.ts] ```ts [/server/api/submit.post.ts]
export default defineEventHandler(async (event) => { export default defineEventHandler(async (event) => {
@ -119,7 +130,28 @@ You can now universally call this API using `$fetch('/api/submit', { method: 'po
We are using `submit.post.ts` in the filename only to match requests with `POST` method that can accept the request body. When using `useBody` within a GET request, `useBody` will throw a `405 Method Not Allowed` HTTP error. We are using `submit.post.ts` in the filename only to match requests with `POST` method that can accept the request body. When using `useBody` within a GET request, `useBody` will throw a `405 Method Not Allowed` HTTP error.
:: ::
## Access Request Cookies ### Handling Requests with query parameters
Sample query `/api/query?param1=a&param2=b`
```ts [/server/api/query.get.ts]
export default defineEventHandler((event) => {
const query = useQuery(event)
return { a: query.param1, b: query.param2 }
})
```
### Get access to the runtimeConfig
```ts [/server/api/foo.ts]
export default defineEventHandler((event) => {
const config = useRuntimeConfig()
return { key: config.KEY }
})
```
### Access Request Cookies
```ts ```ts
export default defineEventHandler((event) => { export default defineEventHandler((event) => {
@ -128,7 +160,9 @@ export default defineEventHandler((event) => {
}) })
``` ```
## Using a nested router ## Advanced Usage Examples
### Using a nested router
```ts [/server/api/hello.ts] ```ts [/server/api/hello.ts]
import { createRouter } from 'h3' import { createRouter } from 'h3'
@ -140,7 +174,20 @@ router.get('/', () => 'Hello World')
export default router export default router
``` ```
## Return a legacy handler or middleware ### Sending streams (experimental)
**Note:** This is an experimental feature and available only within Node.js environments.
```ts [/server/api/foo.get.ts]
import fs from 'node:fs'
import { sendStream } from 'h3'
export default defineEventHandler((event) => {
return sendStream(event, fs.createReadStream('/path/to/file'))
})
```
### Return a legacy handler or middleware
```ts [/server/api/legacy.ts] ```ts [/server/api/legacy.ts]
export default (req, res) => { export default (req, res) => {
@ -162,12 +209,3 @@ export default (req, res, next) => {
::alert{type=warning} ::alert{type=warning}
Never combine `next()` callback with a legacy middleware that is `async` or returns a `Promise`! Never combine `next()` callback with a legacy middleware that is `async` or returns a `Promise`!
:: ::
## Server Utils
Server routes are powered by [unjs/h3](https://github.com/unjs/h3) which comes with a handy set of helpers.
::ReadMore{link="https://www.jsdocs.io/package/h3#package-index-functions" title="Available H3 Request Helpers"}
::
You can add more helpers by yourself inside the `~/server/utils` directory.