AWS Api Gateway 本身提供了跨域资源共享的配置选项,但在本地测试时可能会遇到一些问题。解决方法是通过在 API Gateway 中配置 CORS 并设置本地开发环境的请求头来解决问题。
以下是示例代码:
//API Gateway 配置示例 { "swagger": "2.0", "info": { "version": "1.0", "title": "My API" }, "host": "api.example.com", "basePath": "/v1", "schemes": [ "https" ], "paths": { "/resource": { "options": { "consumes": [ ], "produces": [ "application/json" ], "responses": { "200": { "description": "200 response", "headers": { "Access-Control-Allow-Origin": { "type": "string" }, "Access-Control-Allow-Methods": { "type": "string" }, "Access-Control-Allow-Headers": { "type": "string" }, "Access-Control-Allow-Credentials": { "type": "string" } } } }, "x-amazon-apigateway-integration": { "responses": { "default": { "statusCode": "200", "responseParameters": { "method.response.header.Access-Control-Allow-Origin": "'*'", "method.response.header.Access-Control-Allow-Methods": "'POST,GET,OPTIONS'", "method.response.header.Access-Control-Allow-Headers": "'Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token'", "method.response.header.Access-Control-Allow-Credentials": "'true'" } } }, "requestTemplates": { "application/json": "{"statusCode": 200}" }, "passthroughBehavior": "when_no_templates", "type": "mock" } }, "post": { "consumes": [ "application/json" ], "produces": [ "application/json