Skip to content

Commit

Permalink
Merge pull request #2207 from nightscout/wip/enable-cors
Browse files Browse the repository at this point in the history
option to enable CORS
  • Loading branch information
jasoncalabrese authored Nov 8, 2016
2 parents a242b31 + c970cb7 commit 1b1da56
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ Community maintained fork of the
- [`pump` (Pump Monitoring)](#pump-pump-monitoring)
- [`openaps` (OpenAPS)](#openaps-openaps)
- [`loop` (Loop)](#loop-loop)
- [`cors` (CORS)](#cors-cors)
- [Extended Settings](#extended-settings)
- [Pushover](#pushover)
- [IFTTT Maker](#ifttt-maker)
Expand Down Expand Up @@ -400,6 +401,9 @@ To learn more about the Nightscout API, visit https://YOUR-SITE.com/api-docs.htm
* `LOOP_URGENT` (`60`) - The number of minutes since the last loop that needs to be exceeded before an urgent alarm is triggered
* Add `loop` to `SHOW_FORECAST` to show forecasted BG.

##### `cors` (CORS)
Enabled [CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) so other websites can make request to your Nightscout site, uses these extended settings:
* `CORS_ALLOW_ORIGIN` (`*`) - The list of sites that are allow to make requests

#### Extended Settings
Some plugins support additional configuration using extra environment variables. These are prefixed with the name of the plugin and a `_`. For example setting `MYPLUGIN_EXAMPLE_VALUE=1234` would make `extendedSettings.exampleValue` available to the `MYPLUGIN` plugin.
Expand Down
18 changes: 18 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use strict';

var _ = require('lodash');
var express = require('express');
var compression = require('compression');
var bodyParser = require('body-parser');
Expand All @@ -15,6 +16,23 @@ function create (env, ctx) {
return app;
}

if (env.settings.isEnabled('cors')) {
var allowOrigin = _.get(env, 'extendedSettings.cors.allowOrigin') || '*';
console.info('Enabled CORS, allow-origin:', allowOrigin);
app.use(function allowCrossDomain (req, res, next) {
res.header('Access-Control-Allow-Origin', allowOrigin);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');

// intercept OPTIONS method
if ('OPTIONS' === req.method) {
res.send(200);
} else {
next();
}
});
}

///////////////////////////////////////////////////
// api and json object variables
///////////////////////////////////////////////////
Expand Down

0 comments on commit 1b1da56

Please sign in to comment.