我的cdk项目的一部分是一个Websocket,它获得由POST
请求触发的StepFunction的输出。整个工作流在aws控制台中就像邮递员一样工作。
但是如果我在前端尝试,我收到一个CORS错误:
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我已经设置了我的CORS选项如下:
const api = new apigw.RestApi(this, `${props.devName}BookingApi`, {
// set up CORS
defaultCorsPreflightOptions: {
allowHeaders: [
'Content-Type',
'X-Amz-Date',
'Authorization',
'X-Api-Key',
'X-Amz-Security-Token'
],
statusCode: 200,
allowMethods: ['OPTIONS', 'GET', 'POST', 'DELETE'],
allowCredentials: true,
allowOrigins: Cors.ALL_ORIGINS
},
deploy: true
});
如果我在AWS控制台中手动启用CORS,我不会从前端收到CORS错误。代码中的CORS选项与我手动输入的选项相同。同样奇怪的是,即使我从前端得到CORS错误,WebSocket也会发布StepFunction的输出。
我已经读了这个,但是解决方案不适合我。
edit1: added Errormessage
我找到解决办法了!
设置是这样的。我在apigw.AWSIntegration
选项中遗漏了这一部分:
integrationResponses: [
{
responseParameters: {
'method.response.header.Access-Control-Allow-Origin': "'*'",
},
responseTemplates: {
'application/json': JSON.stringify({
message: '$util.parseJson($input.body)',
state: 'ok',
}),
},
statusCode: '200',
和
methodResponses: [{
statusCode: '200',
// important for CORS
responseParameters: {
'method.response.header.Content-Type': true,
'method.response.header.Access-Control-Allow-Origin': true,
'method.response.header.Access-Control-Allow-Credentials': true
}
}]
in.addMethod
edit1:这个链接帮助我找到了解决方案
edit2: update body ofmethodResponses
: