By jaber
using hapi server -v = 16.7 joi -v = 10.6 deployed in aws ec2, nginx reverse proxy
Server Code in server.js:
'use strict';
//let newrelic = require('newrelic');
let Hapi = require('hapi');
let Routes = require('./Routes');
let Plugins = require('./Plugins');
let Bootstrap = require('./Utils/BootStrap');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
const Inert = require('inert');
const Vision = require('vision');
const HapiSwagger = require('hapi-swagger');
const Pack = require('./package');
const Config = require('./Config');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const server = new Hapi.Server();
server.connection({
port: Config.dbConfig.config.PORT,
routes: {cors: true}
});
let mongoOpts = {
reconnectTries: 60,
reconnectInterval: 2000,
useMongoClient:true
};
mongoose.connect(Config.dbConfig.config.dbURI,mongoOpts, (err, res) => {
if (err) {
console.log("DB Error: ", err);
process.exit(1);
} else {
console.log('MongoDB Connected');
}
});
server.register([
Inert,
Vision,
{
'register': HapiSwagger,
'options': {
info: {
'title': Config.dbConfig.config.SWAGGERNAME,
'version': Pack.version,
description: '',
},
//documentationPath: '/',
tags:[
{
name: 'v2.1.0',
description: 'API'
}
],
grouping: 'tags',
},
}], (err) => {
server.start((err) => {
if (err) {
console.log("Server err----------->", err);
} else {
console.log('Server running at:', server.info.uri);
}
});
});
server.on('response', (request) => {console.log('response===>>>:');
if(request.url.path.startsWith('/panel')){
}
else {//console.log('HEADERS===========>:',request.headers);
/* console for checking the params in the request*/
console.log(request.info.remoteAddress + ': ' + request.method.toUpperCase() +
' ' + request.url.path + ' --> ' + request.response.statusCode);
console.log('Request payload:', request.payload);
}
});
process.on('uncaughtException', function (err) {
console.log(err);
});
server.register(Plugins, function (err) {
if (err) {
server.error('Error while loading plugins : ' + err)
} else {
server.log('info', 'Plugins Loaded')
}
});
server.register(Inert, function (err) {
if (err) {
throw err;
}
server.route(Routes);
});
server.route([
{
method: 'GET',
path: '/{param*}', /* show error page */
handler: function (req, res) {
res.file('./error.html')
}
},
{
path: "/panel/{path*}",
method: "GET",
handler: { /* open admin panel index from panel path*/
directory: {
path: ['./_admin'],
listing: false,
index: ['index.html']
}
}
}
]);
This is deployed in AWS-EC2, with Nginx reverse proxy.When we hit POST request with payload, working fine in localhost and saves data to MongoDB. But when we hit same POST method from another domain against ec2 deployed server, the below error is showing in pm2 logs. It seems its responding with null before running the controller.
Error in pm2 logs, when we hit POST method:
TypeError: Cannot read property 'statusCode' of null
at /var/www/html/vhosts/custom_BE_ecommerce/api/server.js:123:65
at Object.internals.handler (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:283:33)
at invoke (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:255:23)
at each (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:259:13)
at Object.exports.parallel (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/items/lib/index.js:70:13)
at Object.internals.emit (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:276:18)
at module.exports.internals.Server.internals.Podium._emit (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:156:15)
at each (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:197:47)
at Object.exports.parallel (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/items/lib/index.js:70:13)
at relay (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:198:15)
at Object.internals.emit (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:202:16)
at internals.emitEmitter (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:303:15)
at processTicksAndRejections (node:internal/process/task_queues:79:21)
Need help on this issue.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Hello,
The issue you’re experiencing with your Hapi server deployed on AWS EC2, where POST requests are failing with a TypeError: Cannot read property 'statusCode' of null, indicates a problem in handling the response object. This issue is not present in your local environment but occurs in the production environment, which suggests a potential discrepancy between the two setups or an issue with the way the requests are handled or proxied through Nginx.
Here are some steps and considerations to debug and resolve this issue:
Ensure that Nginx is correctly configured to proxy POST requests to your Hapi server. The configuration should include proper handling of request headers and body data.
Check if there’s any specific setting in Nginx that might be altering or blocking the payload of POST requests.
Ensure that the proxy_pass directive in Nginx is correctly pointing to the Hapi server’s address and port.
Since you’re using PM2 for process management, use PM2 logs to inspect more detailed logs of your application. This might give you more insight into what’s happening when the POST request is made.
pm2 logs [app-name]
Look for any errors or unusual entries around the time the POST requests are made.
Use tools like Postman or curl to manually test the API endpoints from the EC2 server. This can help you determine if the issue is with the request itself or the server’s handling of the request.
curl --location --request POST 'http://localhost:8000/test' --header 'Content-Type: application/json' --data-raw '{"test":"value"}'
Besides that, a few other things that I could suggest would be:
Check your EC2 instance’s security groups and network ACLs to ensure they allow inbound and outbound traffic on the required ports.
Review the differences between your local and production environments. Differences in Node.js versions, installed packages, or environment variables can lead to different behaviors.
Ensure that all routes and middleware in your Hapi application are properly handling exceptions. An unhandled exception might cause the response object to be null.
Consider upgrading Hapi and other dependencies to the latest stable versions if you’re using older versions. Sometimes, bugs in certain versions might cause unexpected issues.
Temporarily enable more detailed error reporting or logging in your Hapi application to get more insight into the error.
Best,
Bobby
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.