Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
masotrix opened this issue Sep 25, 2023 · 0 comments
Open

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

masotrix opened this issue Sep 25, 2023 · 0 comments

Comments

@masotrix
Copy link

masotrix commented Sep 25, 2023

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 ([email protected])

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  ║
╚══════════╧═════════╧═══════════╝
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant