Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions lib/http-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,15 +99,24 @@ function HttpServer(options) {
}

if (options.cors) {
this.headers['Access-Control-Allow-Origin'] = '*';
this.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Range';
if (options.corsHeaders) {
options.corsHeaders.split(/\s*,\s*/)
.forEach(function (h) { this.headers['Access-Control-Allow-Headers'] += ', ' + h; }, this);
}
before.push(corser.create(options.corsHeaders ? {
requestHeaders: this.headers['Access-Control-Allow-Headers'].split(/\s*,\s*/)
} : null));
var corserOptions = {
// For CORS, we need to mirror the Origin instead of sending the wildcard `*`.
// Because, some browsers don't permit wildcards on certain request types.
// https://github.com/http-party/http-server/issues/729
// corser's `origins` option mirrors the Origin back in Access-Control-Allow-Origin.
origins: function (_origin, callback) {
callback(null, true);
}
};
if (options.corsHeaders) {
corserOptions.requestHeaders = this.headers['Access-Control-Allow-Headers'].split(/\s*,\s*/);
}
before.push(corser.create(corserOptions));
}

if (options.robots) {
Expand Down
14 changes: 10 additions & 4 deletions test/cors.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,13 @@ test('cors set to true', (t) => {
httpServer.listen(() => {
const port = httpServer.address().port;
const uri = `http://localhost:${port}/subdir/index.html`;
request.get({ uri }, (err, res) => {
request.get({
uri,
headers: {'Origin': 'https://abc.example.com:7777'},
}, (err, res) => {
t.ifError(err);
t.equal(res.statusCode, 200);
t.equal(res.headers['access-control-allow-origin'], '*');
t.equal(res.headers['access-control-allow-origin'], 'https://abc.example.com:7777');
t.equal(res.headers['access-control-allow-headers'], 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since');
});
});
Expand All @@ -105,10 +108,13 @@ test('CORS set to true', (t) => {
httpServer.listen(() => {
const port = httpServer.address().port;
const uri = `http://localhost:${port}/subdir/index.html`;
request.get({ uri }, (err, res) => {
request.get({
uri,
headers: {'Origin': 'https://abc.example.com:7777'},
}, (err, res) => {
t.ifError(err);
t.equal(res.statusCode, 200);
t.equal(res.headers['access-control-allow-origin'], '*');
t.equal(res.headers['access-control-allow-origin'], 'https://abc.example.com:7777');
t.equal(res.headers['access-control-allow-headers'], 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since');
});
});
Expand Down