API 网关 - GET 仅适用于根,不适用于资源

问题描述 投票:0回答:1

我正在尝试创建 API Gateway Lambda。这是我的 CDK 的片段,可以帮助您了解我的应用程序:

    const getGenericTournamentsLambdaFn = new lambda.Function(this, 'GetGenericTournamentsLambda', {
      functionName: "GetGenericTournaments",
      runtime: lambda.Runtime.NODEJS_16_X,
      code: lambda.Code.fromAsset("../src"),
      handler: "get_generic_tournaments.handler",
      environment: {
      }
    });

    const api = new apigateway.RestApi(this, "ATPPredictionsService", {
      restApiName: "ATPPredictionsService",
      description: "Provides APIs for saving and fetching API predictions"
    });


    // works
    api.root.addMethod('GET', new apigateway.LambdaIntegration(getGenericTournamentsLambdaFn, {
      requestTemplates: { "text/html": '{ "statusCode": "200"}' }
    }));

   // doesn't work - exact same Lambda!
  const getGenericTournamentsResource = api.root.addResource('getgenerictournaments');
    getGenericTournamentsResource.addMethod('GET', new apigateway.LambdaIntegration(getGenericTournamentsLambdaFn, {
      requestTemplates: { "text/html": '{ "statusCode": "200"}' }
    }));

我不明白为什么只有 root 方法有效,而其他方法却得到 404。有什么想法吗?

lambda aws-cdk api-gateway
1个回答
0
投票

我的例子中的问题是由于处理程序没有指向正确的端点。如果使用路由,则需要为资源端点提供处理程序。就我而言:

const awsServerlessExpress = require('aws-serverless-express');
const express = require('express');
const cors = require("cors");
const endpoints = require('./endpoints');

const app = express();

app.use(cors({ origin: '*' }));

// must be `/getgenerictournaments` not `/`
app.get('/getgenerictournaments', async (req, res) => {
    endpoints.get_generic_tournaments_handler(req, res);
})

const server = awsServerlessExpress.createServer(app);

exports.handler = (event, context) =>  awsServerlessExpress.proxy(server, event, context);
© www.soinside.com 2019 - 2024. All rights reserved.