Skip to content

Commit

Permalink
Optionally respond with CORS headers
Browse files Browse the repository at this point in the history
  • Loading branch information
doublesharp committed Jan 27, 2017
1 parent 71cd9c7 commit 84072dd
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 4 deletions.
1 change: 1 addition & 0 deletions lib/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ module.exports = {
noBrowser: false,
host: '127.0.0.1',
secure: false,
cors: false,
static: [],
port: 1307,
pathIndex: '',
Expand Down
29 changes: 25 additions & 4 deletions lib/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,10 @@ module.exports = class Server extends EventEmitter {
{
short: 'st',
long: 'static'
},
{
short: 'c',
long: 'cors'
}
];

Expand Down Expand Up @@ -204,6 +208,8 @@ module.exports = class Server extends EventEmitter {
threshold: '1kb'
}));

this._initCors();

this.opts.static.forEach((p) => {
this._app.use(express.static(p, {
index: false
Expand All @@ -215,22 +221,37 @@ module.exports = class Server extends EventEmitter {
this._app.get(/.+/, (req, res) => this._sendIndex(req, res));
}

_initCors() {
if (this.opts.cors) {
this._app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', req.headers.origin || '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Authorization,X-Requested-With,Content-Type');
res.setHeader('Access-Control-Allow-Credentials', true);
if (req.method === 'OPTIONS') {
return res.status(200).end();
}
return next();
});
}
}

_initProxy() {
if (this.opts.proxy) {
this._app.all(this.opts.proxyWhen, (req, res) => {
this.emit('proxy', {req: req});
this._proxyServer.web(req, res);
})
});

this._proxyServer.on('proxyReq', (proxyReq, req) => {
req._proxyReq = proxyReq;
})
});

this._proxyServer.on('error', (err, req, res) => {
this._proxyServer.on('error', (err, req, res) => {
if (req.socket.destroyed && err.code === 'ECONNRESET') {
req._proxyReq.abort();
}
})
});
}
}

Expand Down
1 change: 1 addition & 0 deletions test/server_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ describe('server', () => {
expect(_server.opts.host).to.equal('127.0.0.1');
expect(_server.opts.port).to.equal(1307);
expect(_server.opts.secure).to.equal(false);
expect(_server.opts.cors).to.be.false;
expect(_server.opts.quiet).to.be.false;
expect(_server.opts.pathIndex).to.equal('');
expect(_server.opts.noBrowser).to.equal(false);
Expand Down

0 comments on commit 84072dd

Please sign in to comment.