Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k 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?


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

1 Reply

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;
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...