Skip to content
This repository has been archived by the owner on Oct 11, 2022. It is now read-only.

Add package for auto CORS headers #146

Open
wants to merge 1 commit into
base: devel
Choose a base branch
from
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
53 changes: 53 additions & 0 deletions packages/rest-cors/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# simple:rest-cors

SimpleRestCors middleware for automatically allowing all CORS headers

And responding with a request's `origin` as allowed.

See [this fetch issue](https://github.com/whatwg/fetch/issues/251) for information on it,
in short, allow `*` is not enough, you have to allow the specific origin.

## Usage

Automatically allow CORS for every request from all routes:

```js
JsonRoutes.Middleware.use(JsonRoutes.Middleware.handleCors);
```

Handle CORS from one route:

```js
JsonRoutes.Middleware.use(
'/handle-whatever',
JsonRoutes.Middleware.handleCors
);
```

## Example

```js
JsonRoutes.Middleware.use(
'/handle-whatever',
RestMiddleware.handleCors
);

JsonRoutes.add('get', 'handle-whatever', function () {
JsonRoutes.sendResult(res, { data: { msg: 'ok' } });
});
```

## Usage from client

```
fetch('http://localhost:3000/handle-whatever', {
method: 'post',
body: JSON.stringify({test:1})
}).then(function(response) {
return response.json();
}).then(function(data) {
console.log('Resp:', data);
}).catch(function(e) {
console.error(e);
});
```
26 changes: 26 additions & 0 deletions packages/rest-cors/json_cors_handler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* Handle CORS for any request
*
* @middleware
*/
// eslint-disable-next-line
JsonRoutes.Middleware.handleCors = function (request, response, next) { // jshint ignore:line
const origin = (request.headers && request.headers.origin) || '*';
const newHeaders = {
CORSTEST: origin,
'Cache-Control': 'no-store',
Pragma: 'no-cache',
'Access-Control-Allow-Origin': origin,
'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, Authorization, X-Requested-With',
'Access-Control-Allow-Credentials': 'true',
};
if (!response.headers) response.headers = {};
Object.keys(newHeaders).forEach(k => {
if (!response.headers[k]) {
response.headers[k] = newHeaders[k];
response.setHeader(k, newHeaders[k]);
}
});
next();
};
24 changes: 24 additions & 0 deletions packages/rest-cors/json_cors_handler_tests.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
if (Meteor.isServer) {
JsonRoutes.Middleware.use(
'/handle-whatever',
JsonRoutes.Middleware.handleCors
);

JsonRoutes.add('get', 'handle-whatever', function () {
JsonRoutes.sendResult(res, { data: { msg: 'ok' } });
});
} else { // Meteor.isClient
testAsyncMulti('Middleware - CORS Handling - ' +
'handle standard CORS headers', [
function (test, waitFor) {
HTTP.get(Meteor.absoluteUrl('/handle-whatever'),
waitFor(function (err, resp) {
test.equal(resp.statusCode, 200);
test.equal(resp.headers['Access-Control-Allow-Origin'], origin);
test.equal(resp.headers['Access-Control-Allow-Methods'], 'GET, PUT, POST, DELETE, OPTIONS');
test.equal(resp.headers['Access-Control-Allow-Headers'], 'Origin, X-Requested-With, Content-Type, Accept, Authorization, X-Requested-With');
test.equal(resp.headers['Access-Control-Allow-Credentials'], 'true');
}));
},
]);
}
32 changes: 32 additions & 0 deletions packages/rest-cors/package.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
Package.describe({
name: 'simple:rest-cors',
version: '0.0.1',

// Brief, one-line summary of the package.
summary: 'middleware for handling standard CORS headers',

// URL to the Git repository containing the source code for this package.
git: 'https://github.com/stubailo/meteor-rest',

// By default, Meteor will default to using README.md for documentation.
// To avoid submitting documentation, set this field to null.
documentation: 'README.md',
});

Package.onUse(function (api) {
api.versionsFrom('1.0');
api.use('simple:[email protected]');
api.addFiles('json_cors_handler.js', 'server');
});

Package.onTest(function (api) {
api.use([
'http',
'simple:[email protected]',
'simple:rest-cors',
'test-helpers',
'tinytest',
]);

api.addFiles('json_cors_handler_tests.js');
});