2021-08-11 21:48:33 +00:00
|
|
|
|
---
|
|
|
|
|
navigation:
|
|
|
|
|
title: API
|
|
|
|
|
---
|
|
|
|
|
|
2021-04-20 12:16:09 +00:00
|
|
|
|
# API Routes
|
2021-06-08 21:57:15 +00:00
|
|
|
|
|
|
|
|
|
Nuxt will automatically read in any files in the `~/server/api` directory to create API endpoints.
|
|
|
|
|
|
2021-06-14 19:12:00 +00:00
|
|
|
|
Each file should export a default function that handles api requests. It can return a promise or JSON data directly (or use `res.end()`).
|
2021-06-08 21:57:15 +00:00
|
|
|
|
|
2021-06-14 19:12:00 +00:00
|
|
|
|
## Examples
|
|
|
|
|
|
|
|
|
|
### Hello world
|
2021-06-08 21:57:15 +00:00
|
|
|
|
|
|
|
|
|
```js [server/api/hello.ts]
|
2021-06-14 19:12:00 +00:00
|
|
|
|
export default (req, res) => 'Hello World'
|
2021-06-08 21:57:15 +00:00
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
See result on http://localhost:3000/api/hello
|
|
|
|
|
|
2021-06-14 19:12:00 +00:00
|
|
|
|
### Async function
|
2021-06-08 21:57:15 +00:00
|
|
|
|
|
|
|
|
|
```js [server/api/async.ts]
|
|
|
|
|
export default async (req, res) => {
|
|
|
|
|
await someAsyncFunction()
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
someData: true
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
2021-06-14 12:31:30 +00:00
|
|
|
|
**Example:** Using Node.js style
|
2021-06-08 21:57:15 +00:00
|
|
|
|
|
2021-06-14 19:12:00 +00:00
|
|
|
|
```ts [server/api/node.ts]
|
|
|
|
|
import type { IncomingMessage, ServerResponse } from 'http'
|
|
|
|
|
|
|
|
|
|
export default async (req: IncomingMessage, res: ServerResponse) => {
|
2021-06-08 21:57:15 +00:00
|
|
|
|
res.statusCode = 200
|
|
|
|
|
res.end('Works!')
|
|
|
|
|
}
|
|
|
|
|
```
|