

# 为 API Gateway 中的 HTTP API 配置 CORS
<a name="http-api-cors"></a>

[跨源资源共享 (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) 是一项浏览器安全特征，该特征限制从在浏览器中运行的脚本启动的 HTTP 请求。如果您无法访问自己的 API 并收到包含 `Cross-Origin Request Blocked` 的错误消息，则可能需要启用 CORS。有关更多信息，请参阅[什么是 CORS？](https://aws.amazon.com/what-is/cross-origin-resource-sharing/)。

通常需要 CORS 以构建 Web 应用程序来访问托管在不同域或源上的 API。您可以启用 CORS 以允许从托管在不同域上的 Web 应用程序发出对 API 的请求。例如，如果您的 API 托管在 `https://{api_id}.execute-api.{region}.amazonaws.com/` 上，并且您希望从托管在 `example.com` 上的 Web 应用程序调用 API，您的 API 必须支持 CORS。

如果您为 API 配置 CORS，即使没有为 API 配置 OPTIONS 路由，API Gateway 也会自动向预检 OPTIONS 请求发送响应。对于 CORS 请求，API Gateway 将已配置的 CORS 标头添加到来自集成的响应中。

**注意**  
如果您为 API 配置 CORS，则 API Gateway 忽略从后端集成返回的 CORS 标头。

您可以在 CORS 配置中指定以下参数。要使用 API Gateway HTTP API 控制台添加这些参数，请在输入值后选择**添加**。


| CORS 标头 | CORS 配置属性 | 示例值 | 
| --- | --- | --- | 
|  Access-Control-Allow-Origin  |  allowOrigins  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/apigateway/latest/developerguide/http-api-cors.html)  | 
|  Access-Control-Allow-Credentials  |  allowCredentials  |  true  | 
|  Access-Control-Expose-Headers  |  exposeHeaders  |  date、x-api-id、\$1  | 
|  Access-Control-Max-Age  |  maxAge  |  300  | 
|  Access-Control-Allow-Methods  |  allowMethods  |  GET、POST、DELETE\$1  | 
|  Access-Control-Allow-Headers  |  allowHeaders  |  authorization、\$1  | 

要返回 CORS 标头，您的请求必须包含 `origin` 标头。对于 `OPTIONS` 方法，您的请求必须包含 `origin` 标头和 `Access-Control-Request-Method` 标头。

您的 CORS 配置可能类似以下内容：

![\[HTTP API 的 CORS 配置\]](http://docs.aws.amazon.com/zh_cn/apigateway/latest/developerguide/images/http-cors-console.png)


## 使用 `$default` 路由和授权方为 HTTP API 配置 CORS
<a name="http-api-cors-default-route"></a>

您可以为 HTTP API 的任何路由启用 CORS 并配置授权。当您为 [`$default` 路由](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-routes.html#http-api-develop-routes.default)启用 CORS 和授权时，需要注意一些特殊事项。`$default` 路由捕获对所有尚未显式定义的方法和路由的请求，包括 `OPTIONS` 请求。要支持未经授权的 `OPTIONS` 请求，请向 API 添加一条不需要授权的 `OPTIONS /{proxy+}` 路由，并向该路由附加一个集成。`OPTIONS /{proxy+}` 路由的优先级高于 `$default` 路由。因此，它允许客户端在未经授权的情况下向您的 API 提交 `OPTIONS` 请求。有关路由优先级的更多信息，请参阅 [路由 API 请求](http-api-develop-routes.md#http-api-develop-routes.evaluation)。

## 使用 AWS CLI 为 HTTP API 配置 CORS
<a name="http-api-cors.example"></a>

以下 [update-api](https://docs.aws.amazon.com/cli/latest/reference/apigatewayv2/update-api.html) 命令启用来自 `https://www.example.com` 的 CORS 请求。

**Example**  

```
aws apigatewayv2 update-api --api-id api-id --cors-configuration AllowOrigins="https://www.example.com"
```

有关更多信息，请参阅 Amazon API Gateway 版本 2 API 参考中的 [CORS](https://docs.aws.amazon.com/apigatewayv2/latest/api-reference/apis-apiid.html#apis-apiid-model-cors)。