Hapijs: Not running at local host

1.4k views Asked by At

Here is my server,

Can anybody suggest me how can i run it on localhost?

This is my server.js file code

var Hapi = require('hapi');
var Path = require('path');
var server = new Hapi.Server({connections: {
routes: {
    files: {
        relativeTo: Path.join(__dirname,'public')
    }
  }
 }});
 server.connection({ port: 3000 });
 var mongoose = require("mongoose");
  var routes = require('./Routes/Route');


 mongoose.connect('mongodb://localhost/test', function(err, db) {
  if(!err) {
     console.log("We are connected");
   }
});

 server.views({
  engines: {
      html: require('handlebars')
  },
   path: Path.join(__dirname,'/Html')
});

 server.route(routes);

 server.start(function () {
   console.log('Server running at:', server.info.uri);
 });
2

There are 2 answers

0
Julian Lannigan On

With a few modifications to your code I was able to start up your server with no problem. I removed the routes and just ensured that the server started and that I could at least get a 404 from the server. All of which I accomplished.

If you are concerned about what you have printing out to the console, that is because that is Hapi's attempt at finding your machine's public hostname. See this documentation.

Now if you would like to prevent all external traffic from your hitting your server, you will need to set the address in the server.connection function call.

It'll look like this:

server.connection({ port: 3000, address: '127.0.0.1' });
0
Marcus Poehls On

To run your server only on localhost and not accepting external requests, you can set the host field within the server.connection configuration. Like this:

server.connection({  
  host: 'localhost',
  port: 3000
})

This tutorial helps you to get a basic hapi server started just on localhost :)

https://futurestud.io/tutorials/hapi-get-your-server-up-and-running