diff --git a/lib/options.js b/lib/options.js index 72a0a0e..3d964a7 100644 --- a/lib/options.js +++ b/lib/options.js @@ -4,6 +4,7 @@ module.exports = { noBrowser: false, host: '127.0.0.1', secure: false, + cors: false, static: [], port: 1307, pathIndex: '', diff --git a/lib/server.js b/lib/server.js index 79c8a7f..594d399 100644 --- a/lib/server.js +++ b/lib/server.js @@ -132,6 +132,10 @@ module.exports = class Server extends EventEmitter { { short: 'st', long: 'static' + }, + { + short: 'c', + long: 'cors' } ]; @@ -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 @@ -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(); } - }) + }); } } diff --git a/test/server_test.js b/test/server_test.js index af6cd85..070466b 100644 --- a/test/server_test.js +++ b/test/server_test.js @@ -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);