Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

amazon web services - How to check http request method using API Gateway v2

My Architecture:

  • AWS HTTP API w/ reverse proxy integration
  • Plain Lambda function
  • Postman or browser

I'm trying to check the request method to handle actions, based on this answer they recomm

'use strict';

const AWS = require('aws-sdk');
const dynamo = new AWS.DynamoDB.DocumentClient();

exports.handler = async (event) => {

    switch (event.httpMethod) {
        case 'GET':
            break;
        default:
            throw new Error(`@@@@ Unsupported method "${event.httpMethod}"`);
    }
    return {
        statusCode: 200,
        body: JSON.stringify({message: 'Success'})
    };
};

I pasted that code just like that in my lambda and it doesn't work, I get this error in the logs:

"errorMessage": "@@@@ Unsupported method "undefined"",

That lambda is triggered by my HTTP API and the route has GET method.

If I return the event, I can see that the method is GET or POST, or whatever, look:

enter image description here

Anyone has any idea what's going on?

question from:https://stackoverflow.com/questions/65855161/how-to-check-http-request-method-using-api-gateway-v2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Input Object Schema for HTTP api (v2) is different to REST api (from your link).

For a Http api, method can be obtained from event.requestContext.http.method

so, it will look like this.

exports.handler = async (event) => {
    console.log('event',event);
    switch (event.requestContext.http.method) {
        case 'GET':
            console.log('This is a GET Method');
            break;
        default:
            throw new Error(`@@@@ Unsupported method "${event.httpMethod}"`);
    }
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...