-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
69 lines (60 loc) · 1.71 KB
/
server.js
File metadata and controls
69 lines (60 loc) · 1.71 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
const jwt = require('express-jwt');
const express = require('express');
const next = require('next');
const dotenv = require('dotenv');
dotenv.config({
allowEmptyValues: false,
});
const { PORT, JWT_SECRET, NODE_ENV } = process.env;
const port = parseInt(PORT, 10) || 3000;
const isProduction = NODE_ENV === 'production';
const app = next({ dev: !isProduction });
const handle = app.getRequestHandler();
const jwtOptions = {
secret: JWT_SECRET,
getToken: req => {
if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
return req.headers.authorization.split(' ')[1];
}
if (req.query && req.query.token) {
return req.query.token;
}
if (req.cookies && req.cookies.token) {
return req.cookies.token;
}
return null;
}
};
app.prepare().then(() => {
const server = express();
if (isProduction) {
server.use(
jwt(jwtOptions).unless({
method: 'OPTIONS',
}),
);
}
server.use(function (err, req, res, next) {
console.log('check: ', err)
console.log('name: ', err.name)
if (err.name === 'UnauthorizedError') {
res.redirect(302, 'http://token.frontender.info/?to=http://localhost:3000');
}
});
server.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader(
'Access-Control-Allow-Headers',
'Access-Control-Request-Method, X-Requested-With, Content-Type, Authorization',
);
res.setHeader('Access-Control-Allow-Credentials', true);
return next();
});
server.get('*', (req, res) => {
return handle(req, res);
});
server.listen(port, err => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
})