mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-14 01:53:55 +00:00
052edd220d
Co-authored-by: Pooya Parsa <pyapar@gmail.com>
44 lines
838 B
Markdown
44 lines
838 B
Markdown
---
|
||
navigation:
|
||
title: API
|
||
---
|
||
|
||
# API Routes
|
||
|
||
Nuxt will automatically read in any files in the `~/server/api` directory to create API endpoints.
|
||
|
||
Each file should export a default function that handles api requests. It can return a promise or JSON data directly (or use `res.end()`).
|
||
|
||
## Examples
|
||
|
||
### Hello world
|
||
|
||
```js [server/api/hello.ts]
|
||
export default (req, res) => 'Hello World'
|
||
```
|
||
|
||
See result on http://localhost:3000/api/hello
|
||
|
||
### Async function
|
||
|
||
```js [server/api/async.ts]
|
||
export default async (req, res) => {
|
||
await someAsyncFunction()
|
||
|
||
return {
|
||
someData: true
|
||
}
|
||
}
|
||
```
|
||
|
||
**Example:** Using Node.js style
|
||
|
||
```ts [server/api/node.ts]
|
||
import type { IncomingMessage, ServerResponse } from 'http'
|
||
|
||
export default async (req: IncomingMessage, res: ServerResponse) => {
|
||
res.statusCode = 200
|
||
res.end('Works!')
|
||
}
|
||
```
|