index.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. 'use strict'
  2. import path from 'path'
  3. import express from 'express'
  4. import compression from 'compression'
  5. import serveStatic from 'serve-static'
  6. import helmet from 'helmet'
  7. import cors from 'cors'
  8. import routes from './routes'
  9. import { errorHandler } from './functions'
  10. import { apiPrefix, serverPort, serveClient, imagesPath } from '../config'
  11. const app = express()
  12. // Use gzip compression to improve performance
  13. app.use(compression())
  14. // Enhance the app security by setting some HTTP headers
  15. app.use(helmet())
  16. if (serveClient) {
  17. // Serve client files (Client is local)
  18. app.use('/', express.static(path.resolve(__dirname, '../dist')))
  19. }
  20. else {
  21. // Don't serve client files (Client is remote)
  22. // Turn "Cross-origin resource sharing" on to allow the remote client to connect to the API
  23. app.use(cors())
  24. }
  25. // Serve images. "serve-static" is used because it caches images ("express.static" doesn't)
  26. app.use(serveStatic(imagesPath))
  27. // Load all the API routes in the server
  28. app.use(apiPrefix, routes)
  29. // Error handler (Middleware called when throwing in another middleware)
  30. app.use(errorHandler)
  31. // Start the server on the configured port
  32. app.listen(serverPort, () => console.log('The server was started on http://localhost:' + serverPort))