提交 83a3903f 编写于 作者: L Lukáš Huvar 提交者: Joe Haddad

HTTP methods docs and REST example (#8108)

* HTTP methods docs and REST example

* Update packages/next/README.md
Co-Authored-By: NJoe Haddad <timer150@gmail.com>

* Update examples/api-routes-rest/README.md
Co-Authored-By: NJoe Haddad <timer150@gmail.com>

* Fix standard
上级 f8b56da7
# API routes with REST
## How to use
### Using `create-next-app`
Execute [`create-next-app`](https://www.npmjs.com/package/create-next-app) with [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) or [npx](https://github.com/zkat/npx#readme) to bootstrap the example:
```bash
npx create-next-app --example api-routes-rest api-routes-rest-app
# or
yarn create next-app --example api-routes-rest api-routes-rest-app
```
### Deploy to Now
Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download))
```bash
now
```
## The idea behind the example
Next.js ships with [API routes](https://github.com/zeit/next.js#api-routes), which provide an easy solution to build your own `API`. This example shows how it can be used to create your [REST](https://en.wikipedia.org/wiki/Representational_state_transfer) api.
{
"name": "api-routes-rest",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"isomorphic-unfetch": "3.0.0",
"next": "latest",
"react": "^16.8.6",
"react-dom": "^16.8.6"
},
"license": "ISC"
}
export default (req, res) => {
const {
query: { id, name },
method
} = req
switch (method) {
case 'GET':
// Get data from your database
res.status(200).json({ id, name: `User ${id}` })
break
case 'PUT':
// Update or create data in your database
res.status(200).json({ id, name: name || `User ${id}` })
break
default:
res.setHeader('Allow', ['GET', 'PUT'])
res.status(405).end(`Method ${method} Not Allowed`)
}
}
// Fake users data
const users = [
{
id: 1
},
{ id: 2 },
{ id: 3 }
]
export default (req, res) => {
// Get data from your database
res.status(200).json(users)
}
import fetch from 'isomorphic-unfetch'
import Link from 'next/link'
const Index = ({ users }) => (
<ul>
{users.map(user => (
<li key={user.id}>
<Link href='/user/[id]' as={`/user/${user.id}`}>
<a>{`User ${user.id}`}</a>
</Link>
</li>
))}
</ul>
)
Index.getInitialProps = async () => {
const response = await fetch('http://localhost:3000/api/users')
const users = await response.json()
return { users }
}
export default Index
import fetch from 'isomorphic-unfetch'
const User = ({ user }) => <div>{user.name}</div>
User.getInitialProps = async ({ query: { id } }, res) => {
const response = await fetch(`http://localhost:3000/api/user/${id}`)
const user = await response.json()
return { user }
}
export default User
......@@ -1041,6 +1041,7 @@ export default withRouter(MyLink)
<li><a href="/examples/api-routes-micro">API routes with micro</a></li>
<li><a href="/examples/api-routes-middleware">API routes with middleware</a></li>
<li><a href="/examples/api-routes-graphql">API routes with GraphQL server</a></li>
<li><a href="/examples/api-routes-rest">API routes with REST</a></li>
</ul>
</details>
......@@ -1064,6 +1065,18 @@ export default (req, res) => {
- `res` refers to [NextApiResponse](https://github.com/zeit/next.js/blob/v9.0.0/packages/next-server/lib/utils.ts#L168-L178) which extends [http.ServerResponse](https://nodejs.org/api/http.html#http_class_http_serverresponse)
To handle different HTTP methods for API calls you can access `req.method` in your resolver function:
```js
export default (req, res) => {
if (req.method === 'POST') {
// Process your POST request
} else {
// Handle the rest of your HTTP methods
}
}
```
> **Note**: API Routes [do not specify CORS headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS), so they'll be **same-origin only** by default.
> You can customize this behavior by wrapping your export with CORS middleware.
> We provide an [example of this below](#api-middlewares).
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册