Browse Source

Finished work on CORS

Finished work on CORS
Brendan Abolivier 8 years ago
parent
commit
bc1f243386
3 changed files with 16 additions and 11 deletions
  1. 1
    0
      package.json
  2. 12
    9
      server.js
  3. 3
    2
      settings.example.json

+ 1
- 0
package.json View File

@@ -17,6 +17,7 @@
17 17
   },
18 18
   "dependencies": {
19 19
     "body-parser": "1.15.2",
20
+    "cors": "2.8.1",
20 21
     "express": "4.14.0",
21 22
     "node-minify": "1.3.9",
22 23
     "nodemailer": "2.4.2",

+ 12
- 9
server.js View File

@@ -5,6 +5,7 @@ var settings    = require('./settings');
5 5
 
6 6
 // Web server
7 7
 var bodyParser  = require('body-parser');
8
+var cors        = require('cors');
8 9
 var express     = require('express');
9 10
 var app = express();
10 11
 
@@ -29,15 +30,14 @@ app.use(express.static('front'));
29 30
 // Body parsing
30 31
 app.use(bodyParser.urlencoded({ extended: true }));
31 32
 app.use(bodyParser.json());
32
-
33
-
34
-// Allow cross-origin requests. Wildcard for now, we'll see if we can improve
35
-// that.
36
-app.all('/*', function(req, res, next) {
37
-    res.header('Access-Control-Allow-Origin', '*');
38
-    res.header('Access-Control-Allow-Headers', 'Content-Type')
39
-    next();
40
-});
33
+// Allow cross-origin requests.
34
+var corsOptions = {
35
+  origin: settings.formOrigin,
36
+  optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
37
+};
38
+app.use(cors(corsOptions));
39
+// Taking care of preflight requests
40
+app.options('*', cors(corsOptions));
41 41
 
42 42
 
43 43
 // A request on /register generates a token and store it, along the user's
@@ -64,6 +64,9 @@ app.get('/register', function(req, res, next) {
64 64
 
65 65
 // A request on /send with user input = mail to be sent
66 66
 app.post('/send', function(req, res, next) {
67
+    // Response will be JSON
68
+    res.header('Access-Control-Allow-Headers', 'Content-Type');
69
+    
67 70
     if(!checkBody(req.body)) {
68 71
         return res.status(400).send();
69 72
     }

+ 3
- 2
settings.example.json View File

@@ -5,12 +5,13 @@
5 5
         "port": 465,
6 6
         "secure": true,
7 7
         "auth": {
8
-            "user": "noreply@noreply.tld",
8
+            "user": "noreply@example.tld",
9 9
             "pass": "hackme"
10 10
         }
11 11
     },
12 12
     "recipients": [
13 13
         "you@example.tld",
14 14
         "someone.else@example.com"
15
-    ]
15
+    ],
16
+    "formOrigin": "https://example.tld"
16 17
 }