-
Notifications
You must be signed in to change notification settings - Fork 0
/
server copy 2.js
63 lines (51 loc) · 1.95 KB
/
server copy 2.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
53
54
55
56
57
58
59
60
61
62
63
const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')
const dev = process.env.NODE_ENV !== 'production'
const port = process.env.PORT || 9999;
const hostname = process.env.HOST || `localhost`;
// when using middleware `hostname` and `port` must be provided below
function ensureSecure(req, res, next) {
console.log('x-forwarded-proto:', req.headers["x-forwarded-proto"]); // Debug log
if (req.headers["x-forwarded-proto"] === "https" || req.headers["x-forwarded-proto"] === undefined) {
// Request was via https, so do no special handling
handle(req, res, `https://${req.headers.host}${req.url}` )
} else {
// Redirect to https
res.redirect('https://' + req.hostname + req.url);
}
}
const app = next({ dev, hostname, port })
// Apply the middleware only in production
const handle = app.getRequestHandler()
if (process.env.NODE_ENV === 'production') {
app.use(ensureSecure);
}
app.prepare().then(() => {
createServer(async (req, res) => {
try {
// Be sure to pass `true` as the second argument to `url.parse`.
// This tells it to parse the query portion of the URL.
const parsedUrl = parse(req.url, true)
const { pathname, query } = parsedUrl
if (pathname === '/a') {
await app.render(req, res, '/a', query)
} else if (pathname === '/b') {
await app.render(req, res, '/b', query)
} else {
await handle(req, res, parsedUrl)
}
} catch (err) {
console.error('Error occurred handling', req.url, err)
res.statusCode = 500
res.end('internal server error')
}
})
.once('error', (err) => {
console.error(err)
process.exit(1)
})
.listen(port, () => {
console.log(`> Ready on http://${hostname}:${port}`)
})
})