# 使用 OpenAPI 代理

GitBook 可以代理 **对其进行测试** 请求，因此即使你的 API 服务器不支持 CORS 也能正常工作。

### 为什么会有这个功能

除非 API 服务器通过 CORS 响应头允许，否则浏览器会阻止跨域请求。若未配置 CORS， **对其进行测试** 请求会在浏览器中失败。代理会通过 GitBook 在服务器端路由这些请求，从而绕过该限制。

### 为整个规范启用代理

添加 `x-enable-proxy: true` 到你的 OpenAPI 规范根部。

<pre class="language-yaml"><code class="lang-yaml">openapi: '3.0.3'
<strong>x-enable-proxy: true
</strong>info:
  title: Example API
  version: '1.0.0'
servers:
  - url: https://api.example.com
</code></pre>

### 为特定操作启用或禁用

添加 `x-enable-proxy` 在某个操作上。

<pre class="language-yaml"><code class="lang-yaml">openapi: '3.0.3'
info:
  title: Example API
  version: '1.0.0'
servers:
  - url: https://api.example.com
paths:
  /reports:
    get:
      summary: List reports
<strong>      x-enable-proxy: true
</strong>      responses:
        '200':
          description: OK
    post:
      summary: Create report
<strong>      x-enable-proxy: false
</strong>      responses:
        '201':
          description: Created
</code></pre>

{% hint style="info" %}
操作级别 `x-enable-proxy` 优先于根级别的值。
{% endhint %}

### 代理支持什么

GitBook 转发所有 `HTTP` 方法（`GET`, `POST`, `PUT`, `DELETE`, `PATCH`）、请求头、cookie 和请求体。

### 安全性

代理只会将请求转发到规范中 `servers` 数组里列出的 URL。它不能用于访问任意 URL。

{% hint style="info" %}
请确保你的 `servers` 数组包含你要测试的每个基础 URL。如果某个 URL 未列出， **对其进行测试** 发往该主机的请求将绕过代理。
{% endhint %}
