

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 在 API Gateway 中設定 WebSocket API 的路由回應
<a name="apigateway-websocket-api-route-response"></a>

WebSocket 路由可設定為雙向或單向通訊。API Gateway 不會將後端回應傳遞至路由回應，除非您有設定路由回應。

**注意**  
您只能定義 WebSocket API 的 `$default` 路由回應。您可以使用整合回應來操作後端服務的回應。如需詳細資訊，請參閱[整合回應概觀](apigateway-websocket-api-integration-responses.md#apigateway-websocket-api-integration-response-overview)。

您可以使用 API Gateway 主控台或 AWS CLI 或 AWS SDK 來設定路由回應和回應選取表達式。

如需路由回應選擇表達式的詳細資訊，請參閱 [路由回應選擇表達式](apigateway-websocket-api-selection-expressions.md#apigateway-websocket-api-route-response-selection-expressions)。

**Topics**
+ [使用 API Gateway 主控台設定路由回應](#apigateway-websocket-api-route-response-using-console)
+ [使用 設定路由回應 AWS CLI](#apigateway-websocket-api-route-response-using-awscli)

## 使用 API Gateway 主控台設定路由回應
<a name="apigateway-websocket-api-route-response-using-console"></a>

建立 WebSocket API 並將代理 Lambda 函數附加至預設路由之後，您可以使用 API Gateway 主控台設定路由回應：

1. 登入 API Gateway 主控台，在 `$default` 路由上選擇具備代理 Lambda 函數整合的 WebSocket API。

1. 在 **Routes** (路由) 下選擇 `$default` 路由。

1. 選擇**啟用雙向通訊**。

1. 選擇**部署 API**。

1. 將您的 API 部署至階段。

 使用下列 [ wscat](https://www.npmjs.com/package/wscat) 命令來連線到您的 API。如需 `wscat` 的相關資訊，請參閱 [使用 `wscat` 以連接到 WebSocket API 和將訊息傳送到其中](apigateway-how-to-call-websocket-api-wscat.md)。

```
wscat -c wss://{{api-id}}.execute-api.{{us-east-2}}.amazonaws.com/{{test}}
```

 按下 Enter 按鈕以呼叫預設路由。您 Lambda 函數的主體應該會傳回。

## 使用 設定路由回應 AWS CLI
<a name="apigateway-websocket-api-route-response-using-awscli"></a>

以下 [create-route-response](https://docs.aws.amazon.com/cli/latest/reference/apigatewayv2/create-route-response.html) 命令會建立 `$default` 路由的路由回應。您可以使用 [get-apis](https://docs.aws.amazon.com/cli/latest/reference/apigatewayv2/get-apis.html) 和 [get-routes](https://docs.aws.amazon.com/cli/latest/reference/apigatewayv2/get-routes.html) 命令來識別 API ID 和路由 ID。

```
aws apigatewayv2 create-route-response \
    --api-id {{aabbccddee}} \
    --route-id {{1122334 }} \
    --route-response-key '$default'
```

輸出將如下所示：

```
{
    "RouteResponseId": "abcdef",
    "RouteResponseKey": "$default"
}
```