---
title: "访问统计"
image: "https://cwd.js.org/icon.png"
---

> Documentation Index
> Fetch the complete documentation index at: https://cwd.js.org/llms.txt
> Use this file to discover all available pages before exploring further.

# 访问统计

页面访问统计接口，用于记录和分析页面访问数据。

## 记录页面访问

```
POST /api/analytics/visit
```

前端组件在加载时调用此接口，记录页面访问数据，用于后台访问统计分析。

- 方法：`POST`
- 路径：`/api/analytics/visit`
- 鉴权：不需要

**请求头**

| 名称           | 必填 | 示例               |
| -------------- | ---- | ------------------ |
| `Content-Type` | 是   | `application/json` |

**请求体**

```json
{
  "postSlug": "https://example.com/blog/hello-world",
  "postTitle": "博客标题",
  "postUrl": "https://example.com/blog/hello-world"
}
```

**请求头**

| 名称           | 必填 | 示例                         |
| -------------- | ---- | ---------------------------- |
| `Content-Type` | 是   | `application/json`          |
| `X-Site-Id`    | 否   | `blog`                       |

字段说明：

| 字段名      | 类型   | 必填 | 说明                                                                 |
| ----------- | ------ | ---- | -------------------------------------------------------------------- |
| `postSlug`  | string | 是   | 文章唯一标识符，`window.location.origin + window.location.pathname`     |
| `postTitle` | string | 否   | 文章标题，用于后台展示页面名称                                        |
| `postUrl`   | string | 否   | 文章 URL，用于后台展示页面链接和域名统计                              |

**请求头说明：**

| 名称       | 必填 | 说明                       |
| ---------- | ---- | -------------------------- |
| `X-Site-Id` | 否   | 站点 ID，用于多站点数据隔离，默认 `default` |

**成功响应**

- 状态码：`200`

```json
{
  "success": true
}
```

**错误响应**

- 缺少 `postSlug`：

  - 状态码：`400`

  ```json
  {
    "message": "postSlug is required"
  }
  ```

- 服务器内部错误：

  - 状态码：`500`

  ```json
  {
    "message": "记录访问数据失败"
  }
  ```

## 获取页面访问量

```
GET /api/analytics/pv
```

获取指定页面的访问量（PV），用于在前端展示页面访问次数。

- 方法：`GET`
- 路径：`/api/analytics/pv`
- 鉴权：不需要

**查询参数**

| 名称        | 位置  | 类型   | 必填 | 说明                                      |
| ----------- | ----- | ------ | ---- | ----------------------------------------- |
| `post_slug` | query | string | 是   | 文章唯一标识符                            |
| `siteId`    | query | string | 否   | 站点 ID，用于多站点数据隔离，默认 `default` |

**成功响应**

- 状态码：`200`

```json
{
  "pv": 100,
  "postSlug": "https://example.com/blog/hello-world"
}
```

字段说明：

| 字段名     | 类型   | 说明                     |
| ---------- | ------ | ------------------------ |
| `pv`       | number | 页面访问量（PV）         |
| `postSlug` | string | 文章唯一标识符           |

**错误响应**

- 缺少 `post_slug`：

  - 状态码：`400`

  ```json
  {
    "message": "post_slug is required"
  }
  ```

- 服务器内部错误：

  - 状态码：`500`

  ```json
  {
    "message": "获取访问量失败"
  }
  ```

Source: https://cwd.js.org/api/public/analytics/index.mdx
