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