| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- const { createServer } = require('https');
- const { parse } = require('url');
- const next = require('next');
- const fs = require('fs');
- const path = require('path');
- const dev = process.env.NODE_ENV !== 'production';
- const hostname = 'localhost';
- const port = 3000;
- const app = next({ dev, hostname, port });
- const handle = app.getRequestHandler();
- // SSL 证书路径(相对于项目根目录)
- const certDir = path.join(__dirname, '..', 'certs');
- const keyPath = path.join(certDir, 'server.key');
- const certPath = path.join(certDir, 'server.crt');
- app.prepare().then(() => {
- // 检查证书文件是否存在
- if (fs.existsSync(keyPath) && fs.existsSync(certPath)) {
- const httpsOptions = {
- key: fs.readFileSync(keyPath),
- cert: fs.readFileSync(certPath),
- };
- createServer(httpsOptions, async (req, res) => {
- try {
- const parsedUrl = parse(req.url, true);
- await handle(req, res, parsedUrl);
- } catch (err) {
- console.error('Error occurred handling', req.url, err);
- res.statusCode = 500;
- res.end('internal server error');
- }
- }).listen(port, (err) => {
- if (err) throw err;
- console.log(`> Ready on https://${hostname}:${port}`);
- });
- } else {
- console.error('[SSL] 未找到证书文件,无法启动 HTTPS 服务器');
- console.error(`[SSL] 证书路径: ${certPath}`);
- console.error(`[SSL] 私钥路径: ${keyPath}`);
- console.error('[SSL] 请运行: scripts/generate_ssl_cert.bat (Windows) 或 scripts/generate_ssl_cert.sh (Linux/Mac)');
- process.exit(1);
- }
- });
|