Einrichten von CORs mit Lambda API Gateway CDKC#

Ein Treffpunkt für C#-Programmierer
Anonymous
 Einrichten von CORs mit Lambda API Gateway CDK

Post by Anonymous »

Ich versuche, mein API -Gateway in AWS durch die CDK einzurichten. Ich habe es eingerichtet, aber egal was ich versuche, ich kann CORS nicht umgehen, um die Lambda -Funktion auszuführen, die die Datenbank liest. Ich benutze C#, um das zu schreiben. Hier ist der Code: < /p>

Code: Select all

using Constructs;
using Amazon.CDK.AWS.APIGateway;
using Amazon.CDK.AWS.Lambda;
using System.Collections.Generic;

/**
* This stack creates an API Gateway REST API.
* The API has a single resource, /items, which supports GET, POST, and PUT methods.
* Each method is integrated with a Lambda function.
*/

namespace Cdk
{
public class ApiGatewayStack
{
// Need to use RestApiBase instead of RestApi for v1
public RestApiBase Api { get; }

public ApiGatewayStack(Construct scope, Function lambdaFunction)
{
Api = new RestApi(scope, "ServerlessProjApi", new RestApiProps
{
DefaultCorsPreflightOptions = new CorsOptions
{
AllowOrigins = Cors.ALL_ORIGINS,           // Allow all origins
AllowMethods = Cors.ALL_METHODS,           // Allow all methods (GET, POST, PUT, etc.)
AllowHeaders = new[] { "Content-Type", "X-Amz-Date", "Authorization", "X-Api-Key" } // CORS headers
}
});

SetupApiGateway(Api, lambdaFunction);
}

private void SetupApiGateway(RestApiBase api, Function lambdaFunction)
{
var lambdaIntegration = new LambdaIntegration(lambdaFunction);
var options = new MethodOptions
{
AuthorizationType = AuthorizationType.NONE,
MethodResponses = new[] {
new MethodResponse
{
StatusCode = "200",
ResponseParameters = new Dictionary
{
{ "method.response.header.Access-Control-Allow-Origin", true },
{ "method.response.header.Access-Control-Allow-Headers", true },
{ "method.response.header.Access-Control-Allow-Methods", true }
}
}
}
};

// Create /items resource
var items = api.Root.AddResource("items");

// Add methods for /items resource (GET, POST, PUT)
items.AddMethod("GET", lambdaIntegration, options);  // GET /items
items.AddMethod("POST", lambdaIntegration, options); // POST /items
items.AddMethod("PUT", lambdaIntegration, options);  // PUT /items
}
}
}
< /code>
Ich habe zuerst die Restapi -Klasse ausprobiert, aber diese Lösung gesehen, obwohl die Änderung keinen Unterschied machte. Ich kann über meinen Browser auf die API zugreifen, indem ich den Endpunkt eingeben, aber nicht über eine Webseite. Hier ist mein genauer Fehler: < /p>
Access to XMLHttpRequest at 'https://{apicode}.execute-api.us-east-1.amazonaws.com/prod/items' from origin 'http://{my-s3-bucket}.s3-website-us-east-1.amazonaws.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Jede Hilfe wird geschätzt!

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post