weisk
11/7/2015 - 11:23 AM

gulp task connect history api enhanced

gulp task connect history api enhanced

gulp.task 'connect', [], -> connect.server
  root: ['build']
  port: 9000
  livereload: true
  middleware: (connect, opt) -> [
    historyApiFallback = (req, res, next) ->
      headers = req.headers
      rewriteTarget = '/index.html'
      appBaseDir = 'build'

      acceptsHtml = (header) ->
        header.indexOf('text/html') isnt -1 or header.indexOf('*/*') isnt -1

      if req.method isnt 'GET'
        # Not rewriting because the method is not GET'
        return next()

      else if not headers or typeof headers.accept isnt 'string'
        # Not rewriting because the client did not send an HTTP accept header
        return next()

      else if headers.accept.indexOf('application/json') is 0
        # Not rewriting because the client prefers JSON
        return next()

      else if not acceptsHtml headers.accept
        # Not rewriting because the client does not accept HTML
        return next()

      parsedUrl = url.parse req.url
      if parsedUrl.pathname.indexOf('.') isnt -1
        # Not rewriting because the path includes a dot (.) character
        fileName = parsedUrl.href.split(parsedUrl.search).join("")
        fileExists = fs.existsSync appBaseDir + fileName
        if fileExists then return next()

      # rewriting
      req.url = rewriteTarget
      next()
  ]