【发布时间】:2020-10-25 01:54:51
【问题描述】:
我有一个通过 CDK 部署的 API 的 OpenAPI 规范。规范看起来像:
openapi: 3.0.1
info:
title: My API
description: My REST API with CORS enabled
version: 0.1.0
x-amazon-apigateway-cors:
allowOrigins:
- "*"
allowCredentials: true
exposeHeaders:
- "x-apigateway-header"
- "x-amz-date"
- "content-type"
maxAge: 3600
allowMethods:
- "*"
allowHeaders":
- "x-apigateway-header"
- "x-amz-date"
- "content-type"
- "Authorization"
components:
securitySchemes:
lambda:
type: "apiKey"
name: "Authorization"
in: "header"
x-amazon-apigateway-authtype: "custom"
x-amazon-apigateway-authorizer:
authorizerUri: "{{my-lambda-authorizer}}"
authorizerResultTtlInSeconds: 300
type: "token"
paths:
/user/{id}:
get:
summary: Get info of specified user.
parameters:
- in: path
name: id
required: true
schema:
type: string
responses:
'200':
description: OK
content:
application/json:
schema:
$ref: '#/components/schemas/User'
security:
- lambda: []
x-amazon-apigateway-integration:
uri: "{{my-lambda}}"
passthroughBehavior: "when_no_match"
httpMethod: "POST"
type: "aws_proxy"
当我尝试通过fetch() 访问它时,我收到错误Failed to load resource: Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin。
fetch('https://api.example.com/user/1')
.then(response => response.json())
.then((user: User) => {
// do something
})
.catch((err) => {
console.log("Error: " + err);
});
API 可通过api.example.com 访问,我正在使用 Gatsby 在本地运行网站localhost:8000。
AWS docs 似乎表明当我将 x-amazon-apigateway-cors 放在规范的根目录时启用了 CORS,但是当我尝试访问 API 时似乎没有启用(或工作)CORS。如何在无需在控制台中配置的情况下为我的 API 启用 CORS?
【问题讨论】:
标签: amazon-web-services aws-lambda amazon-cloudformation aws-api-gateway aws-cdk