-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathapp.js
52 lines (44 loc) · 1.23 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
const express = require('express');
const cookieParser = require('cookie-parser');
const cors = require('cors');
const app = express();
app.use(cookieParser());
app.use(express.json());
// Add all the hosts that will make requests to the service
const allowedHosts = [
'https://www.mydomain.com'
];
const corsOptions = {
origin: (origin, cb) => {
if (allowedHosts.indexOf(origin) > -1) {
cb(null, true);
} else {
cb(new Error(`CORS error! Attempt to reach API from ${origin}`));
}
},
methods: 'POST',
credentials: true
};
app.options('/', cors(corsOptions));
app.post('/', cors(corsOptions), (req, res, next) => {
const msg = req.body;
const cookies = Array.isArray(msg) ? msg : [msg];
const hasSet = [];
cookies.forEach(c => {
if (typeof c !== 'object') return;
if (!c.hasOwnProperty('name') || !c.hasOwnProperty('value')) {
return;
}
hasSet.push(c.name);
res.cookie(c.name, c.value, c.options);
});
res.status(200).json({msg: `Processed cookies: ${hasSet}`});
});
const PORT = process.env.PORT || '8080';
/* istanbul ignore next */
if (process.env.NODE_ENV !== 'test') {
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
});
}
module.exports = app;