# 请求与响应对象

URL: https://caijiao.org/fastify/core/request-reply
Source: docs/fastify/core/request-reply.md
Description: 详解 Fastify 中的 request 和 reply 对象，用于获取请求信息和构造响应。

在 Fastify 中，每个路由处理函数都会接收两个参数：`request` 和 `reply`。它们分别用于访问客户端请求内容和构建服务端响应。

## request 对象

`request` 提供对请求信息的访问，常用属性包括：

### request.query

获取 URL 查询参数：

```js
// GET /search?q=fastify
fastify.get('/search', async (request) => {
  const { q } = request.query;
  return { result: `You searched: ${q}` };
});
```

### request.params

获取路径参数：

```js
// GET /user/123
fastify.get('/user/:id', async (request) => {
  const { id } = request.params;
  return { userId: id };
});
```

### request.body

获取请求体（用于 POST、PUT 等请求）：

```js
fastify.post('/login', async (request) => {
  const { username, password } = request.body;
  return { username };
});
```

### request.headers

访问请求头：

```js
fastify.get('/header', async (request) => {
  const agent = request.headers['user-agent'];
  return { agent };
});
```

## reply 对象

`reply` 用于设置响应内容、状态码和头部信息等。

### reply.send(data)

发送响应数据：

```js
reply.send({ message: 'Success' });
```

### reply.code(statusCode)

设置响应状态码：

```js
reply.code(201).send({ message: 'Created' });
```

### reply.header(name, value)

设置响应头：

```js
reply.header('X-Custom', 'value').send({ done: true });
```

## 默认行为

如果你使用 `async` 函数并返回一个值，[Fastify](/fastify/) 会自动调用 `reply.send()`：

```js
fastify.get('/', async () => {
  return { hello: 'world' };
});
```

掌握 `request` 和 `reply` 是构建高质量 API 服务的基础。
