Created
November 7, 2015 11:23
-
-
Save weisk/8b8e060b821bb085a3ea to your computer and use it in GitHub Desktop.
gulp task connect history api enhanced
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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