server.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. const { createServer } = require('https');
  2. const { parse } = require('url');
  3. const next = require('next');
  4. const fs = require('fs');
  5. const path = require('path');
  6. const dev = process.env.NODE_ENV !== 'production';
  7. const hostname = 'localhost';
  8. const port = 3000;
  9. const app = next({ dev, hostname, port });
  10. const handle = app.getRequestHandler();
  11. // SSL 证书路径(相对于项目根目录)
  12. const certDir = path.join(__dirname, '..', 'certs');
  13. const keyPath = path.join(certDir, 'server.key');
  14. const certPath = path.join(certDir, 'server.crt');
  15. app.prepare().then(() => {
  16. // 检查证书文件是否存在
  17. if (fs.existsSync(keyPath) && fs.existsSync(certPath)) {
  18. const httpsOptions = {
  19. key: fs.readFileSync(keyPath),
  20. cert: fs.readFileSync(certPath),
  21. };
  22. createServer(httpsOptions, async (req, res) => {
  23. try {
  24. const parsedUrl = parse(req.url, true);
  25. await handle(req, res, parsedUrl);
  26. } catch (err) {
  27. console.error('Error occurred handling', req.url, err);
  28. res.statusCode = 500;
  29. res.end('internal server error');
  30. }
  31. }).listen(port, (err) => {
  32. if (err) throw err;
  33. console.log(`> Ready on https://${hostname}:${port}`);
  34. });
  35. } else {
  36. console.error('[SSL] 未找到证书文件,无法启动 HTTPS 服务器');
  37. console.error(`[SSL] 证书路径: ${certPath}`);
  38. console.error(`[SSL] 私钥路径: ${keyPath}`);
  39. console.error('[SSL] 请运行: scripts/generate_ssl_cert.bat (Windows) 或 scripts/generate_ssl_cert.sh (Linux/Mac)');
  40. process.exit(1);
  41. }
  42. });