Skip to content

Commit

Permalink
Add spa-ignore-assets middleware (tapio#150, tapio#142).
Browse files Browse the repository at this point in the history
  • Loading branch information
tapio committed Nov 5, 2016
1 parent 1420667 commit 4f6d551
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
14 changes: 14 additions & 0 deletions middleware/spa-ignore-assets.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Single Page Apps - redirect to /#/ except when a file extension is given
var path = require('path');
module.exports = function(req, res, next) {
if (req.method !== "GET" && req.method !== "HEAD")
next();
if (req.url !== '/' && path.extname(req.url) === '') {
var route = req.url;
req.url = '/';
res.statusCode = 302;
res.setHeader('Location', req.url + '#' + route);
res.end();
}
else next();
}
40 changes: 40 additions & 0 deletions test/spa.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
var request = require('supertest');
var path = require('path');
var liveServerSpa = require('..').start({
root: path.join(__dirname, "data"),
port: 0,
open: false,
middleware: [ "spa" ]
});
var liveServerSpaIgnoreAssets = require('..').start({
root: path.join(__dirname, "data"),
port: 0,
open: false,
middleware: [ "spa-ignore-assets" ]
});

describe('spa tests', function(){
it('spa should redirect', function(done){
request(liveServerSpa)
.get('/api')
.expect('Location', /\/#\//)
.expect(302, done);
});
it('spa should redirect everything', function(done){
request(liveServerSpa)
.get('/style.css')
.expect('Location', /\/#\//)
.expect(302, done);
});
it('spa-ignore-assets should redirect something', function(done){
request(liveServerSpaIgnoreAssets)
.get('/api')
.expect('Location', /\/#\//)
.expect(302, done);
});
it('spa-ignore-assets should not redirect .css', function(done){
request(liveServerSpaIgnoreAssets)
.get('/style.css')
.expect(200, done);
});
});

0 comments on commit 4f6d551

Please sign in to comment.