Skip to content

Instantly share code, notes, and snippets.

@weisk
Created November 7, 2015 11:23
Show Gist options
  • Save weisk/8b8e060b821bb085a3ea to your computer and use it in GitHub Desktop.
Save weisk/8b8e060b821bb085a3ea to your computer and use it in GitHub Desktop.
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()
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment