|
1 | 1 | /* eslint-disable @typescript-eslint/no-var-requires */
|
| 2 | +const express = require('express'); |
2 | 3 | const next = require('next');
|
| 4 | + |
3 | 5 | const dev = process.env.NEXT_PUBLIC_ENV !== 'production';
|
4 | 6 | const app = next({ dev });
|
5 | 7 | const handle = app.getRequestHandler();
|
6 | 8 |
|
7 |
| -const { parse } = require('url'); |
8 |
| - |
9 |
| -const express = require('express'); |
10 |
| -const expressRouter = express.Router(); |
11 |
| -const server = express(); |
12 |
| -// this is the logger for the server |
13 |
| -var logger = require('pino-http')(); |
| 9 | +const PORT = process.env.PORT || 3000; |
14 | 10 |
|
15 |
| -const NODE_PORT = process.env.NODE_PORT | 3000; |
| 11 | +async function startServer() { |
| 12 | + try { |
| 13 | + await app.prepare(); |
| 14 | + const server = express(); |
16 | 15 |
|
17 |
| -app.prepare().then(() => { |
18 |
| - expressRouter.get('*', (req, res) => { |
19 |
| - // 页面路由 |
20 |
| - logger(req, res); |
21 |
| - const parsedUrl = parse(req.url, true); |
22 |
| - const { pathname, query } = parsedUrl; |
23 |
| - if (pathname.length > 1 && pathname.endsWith('/')) { |
24 |
| - return app.render(req, res, pathname.slice(0, -1), query); |
25 |
| - } else { |
26 |
| - return app.render(req, res, pathname, query); |
27 |
| - } |
28 |
| - }); |
29 |
| - server.use('/', expressRouter); |
| 16 | + // 中间件处理尾部斜杠但不重定向 |
| 17 | + server.use((req, res, next) => { |
| 18 | + if (req.url.length > 1 && req.url.endsWith('/')) { |
| 19 | + req.url = req.url.slice(0, -1); |
| 20 | + } |
| 21 | + next(); |
| 22 | + }); |
30 | 23 |
|
31 |
| - server.all('*', (req, res) => { |
32 |
| - // Be sure to pass `true` as the second argument to `url.parse`. |
33 |
| - // This tells it to parse the query portion of the URL. |
34 |
| - const parsedUrl = parse(req.url, true); |
| 24 | + // 处理所有其他请求 |
| 25 | + server.all('*', (req, res) => handle(req, res)); |
35 | 26 |
|
36 |
| - return handle(req, res, parsedUrl); |
37 |
| - }); |
| 27 | + server.listen(PORT, (err) => { |
| 28 | + if (err) throw err; |
| 29 | + console.log(`> Ready on http://localhost:${PORT}`); |
| 30 | + }); |
| 31 | + } catch (error) { |
| 32 | + console.error('Error starting server:', error); |
| 33 | + process.exit(1); |
| 34 | + } |
| 35 | +} |
38 | 36 |
|
39 |
| - server.listen(NODE_PORT, () => |
40 |
| - console.log('App listening on port ' + NODE_PORT) |
41 |
| - ); |
42 |
| -}); |
| 37 | +startServer(); |
0 commit comments