jeremydaly / lambda-api

Lightweight web framework for your serverless applications
https://serverless-api.com
MIT License
1.41k stars 125 forks source link

Minimum reproducible example for "Method not allowed" error #251

Open masotrix opened 9 months ago

masotrix commented 9 months ago

I have this MRE

// test.js
import http from 'http';
import getLambdaAPI from 'lambda-api';

const getLambdaEvent = req => {
  const event = {
    path: req.url,
    httpMethod: req.method,
    requestContext: {
      http: { method: req.method, path: req.url },
    },
  };

  return event;
};

const api = getLambdaAPI();

api.get('/', (req, res) => {
    const SERVICE_RESPONSE = "API_RUNNING";
    console.log({ SERVICE_RESPONSE });
    //return { SERVICE_RESPONSE: "API_RUNNING" };
    res.status(200).json({ SERVICE_RESPONSE: "API_RUNNING" });
});

const lambdaHandler = async (event, context) => {
    console.log(event);
    console.log({
      ROUTE_CODE: 'LAMBDA_EVENT',
      PATH: event.requestContext?.http?.path,
      METHOD: event.requestContext?.http?.method,
    });

    api.routes(true);
    return await api.run({ event, context });
  };

const handler = async (req, res) => {
  try {

    const lambdaEvent = getLambdaEvent(req);
    const lambdaRes = await lambdaHandler(lambdaEvent, null)

    res.statusCode = lambdaRes.statusCode;
    res.end(lambdaRes.body);

  } catch(SERVER_ERROR) {
    console.log({ SERVER_ERROR });
    res.statusCode = 500;
    res.end(JSON.stringify({ REQUEST_PARSING_ERROR: SERVER_ERROR.toString() }));
  }
}

const server = http.createServer(handler);
server.listen(8080);

When I run it with node test.js and make a GET request with postman to http://localhost:8080 I get {"error":"Method not allowed"}

Can you spot the issue? Me not neither GPT-4 (lambda-api@1.03)

The console says this

api$ node test.js
{
  path: '/',
  httpMethod: 'GET',
  requestContext: { http: { method: 'GET', path: '/' } }
}
{ ROUTE_CODE: 'LAMBDA_EVENT', PATH: '/', METHOD: 'GET' }
╔══════════╤═════════╤═══════════╗
║  METHOD  │  ROUTE  │  STACK    ║
╟──────────┼─────────┼───────────╢
║  GET     │  /      │  unnamed  ║
╚══════════╧═════════╧═══════════╝