7

I'm creating a node.js api server using hapi.js and mongodb and I'm having some trouble to get it working on Amazon EC2. Running it locally works, but if I run it on an EC2 instance I'm getting the error TypeError: Cannot read property 'statusCode' of null

The complete stacktrace is the following:

TypeError: Cannot read property 'statusCode' of null
  at Request._finalize (/home/ec2-user/backend/node_modules/@hapi/hapi/lib/request.js:497:31)
  at Request._reply (/home/ec2-user/backend/node_modules/@hapi/hapi/lib/request.js:434:18)
  at Request._execute (/home/ec2-user/backend/node_modules/@hapi/hapi/lib/request.js:280:14)
  at processTicksAndRejections (node:internal/process/task_queues:93:5)

The strange part is that GET requests are working while PUT, POST and DELETE are throwing the above error. I've setup the server.js as follow:

...
const init = async () => {

    const server = Hapi.server({
        port: 3000,
    });

    //server.route(routes);

    server.route([
      {
        method: "GET",
        path: "/test",
        handler: async (request, h) => {
          return "workin GET";
        },
      },
      {
        method: "PUT",
        path: "/test",
        handler: async (request, h) => {
          return "workin PUT";
        },
      },
      {
        method: "POST",
        path: "/test",
        handler: async (request, h) => {
          return "workin POST";
        },
      },
      {
        method: "DELETE",
        path: "/test",
        handler: async (request, h) => {
          return "workin DELETE";
        },
      },
    ]);

    await server.start();
    console.log('Server running on %s', server.info.uri);
};

process.on('unhandledRejection', (err) => {
    console.log(err);
    process.exit(1);
});

init();

Any solution?

Francesco Re
  • 836
  • 6
  • 22

3 Answers3

14

I've found out that on the EC2 instance I had installed node version 15.5.0 which apparently is not compatible with the latest version of hapi.js (20.0.2).

To fix the issue just install node version 14.15.3.

Francesco Re
  • 836
  • 6
  • 22
  • Hi, thank you very much, you saved me hours. How did you get that hapijs latest version was not compatible with node15.5.0 ? – VirgileD Feb 12 '21 at 08:14
  • @VirgileD Fortunately I had a different version of Node installed on my pc :) – Francesco Re Feb 12 '21 at 08:21
  • I was running a HAPI server locally, was getting the same error. Installed node v14.17.0 using nvm and it worked. – Ayudh Jun 08 '21 at 09:15
1

This is fixed in @hapi/hapi v20.2.1: https://github.com/hapijs/hapi/issues/4319.

Aleksi
  • 4,483
  • 33
  • 45
-1

Just remove @hapi/hapi and re-install it