Refactoring server.js

Moved functions to the bottom of the file. Added error handling