Skip to content

Commit

Permalink
middleware/cors: improve cors middleware.
Browse files Browse the repository at this point in the history
  • Loading branch information
chjj committed Dec 16, 2023
1 parent 3bb3462 commit ef968f5
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 13 deletions.
41 changes: 30 additions & 11 deletions lib/middleware/cors.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,46 @@

'use strict';

const assert = require('bsert');

/**
* CORS middleware.
* @returns {Function}
*/

function cors() {
function cors(options = {}) {
assert(options && typeof options === 'object');
assert(options.origins == null || Array.isArray(options.origins));

const origins = options.origins || [];

for (const origin of origins) {
assert(typeof origin === 'string' && origin.length > 0);
assert(origin !== '*' && origin !== 'null');
}

return async (req, res) => {
const origin = req.headers.origin != null
? req.headers.origin
: '*';
const origin = req.headers.origin || '';

res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader(
'Access-Control-Allow-Methods',
'GET,HEAD,PUT,PATCH,POST,DELETE');
res.setHeader(
'Access-Control-Allow-Headers', 'Authorization,Content-Type,User-Agent');

if (req.method === 'OPTIONS') {
res.setStatus(200);
res.setHeader('Access-Control-Allow-Headers',
'Authorization,Content-Type,User-Agent');
res.setHeader('Access-Control-Allow-Methods',
'GET,HEAD,PUT,PATCH,POST,DELETE');
}

if (origins.length === 0)
res.setHeader('Access-Control-Allow-Origin', origin || '*');
else if (origins.length === 1)
res.setHeader('Access-Control-Allow-Origin', origins[0]);
else if (origins.includes(origin))
res.setHeader('Access-Control-Allow-Origin', origin);

if (req.method === 'OPTIONS') {
res.setHeader('Content-Length', '0');
res.setStatus(204);
res.end();
return;
}
Expand Down
6 changes: 4 additions & 2 deletions lib/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -620,11 +620,12 @@ class Server extends EventEmitter {

/**
* CORS middleware.
* @param {Object} options
* @returns {Function}
*/

cors() {
return middleware.cors();
cors(options) {
return middleware.cors(options);
}

/**
Expand All @@ -650,6 +651,7 @@ class Server extends EventEmitter {
/**
* JSON rpc middleware.
* @param {Object} rpc
* @param {Object} options
* @returns {Function}
*/

Expand Down

0 comments on commit ef968f5

Please sign in to comment.