HTTPS on localhost using NextJS + Express

后端 未结 4 1952
灰色年华
灰色年华 2021-02-06 15:39

System Information

  • Express: 4.16.4
  • NextJS: 8.0.3
  • React: 16.8.4
  • ReactDOM: 16.8.4

Goal

4条回答
  •  庸人自扰
    2021-02-06 16:27

    Our straightforward, switchable implementation:

    const app = require('express')();
    const https = require('https');
    const http = require('http');
    const next = require('next');
    const fs = require('fs');
    const path = require('path');
    
    const HTTPS = true;
    const server = HTTPS
      ? https.createServer(
          {
            key: fs.readFileSync(path.resolve(__dirname, './server.key')),
            cert: fs.readFileSync(path.resolve(__dirname, './server.cert')),
          },
          app
        )
      : http.createServer({}, app);
    
    const port = parseInt(process.env.PORT, 10) || 3000;
    const dev = process.env.NODE_ENV !== 'production';
    const nextApp = next({ dev });
    const nextHandler = nextApp.getRequestHandler();
    
    nextApp.prepare().then(() => {
      app.get('/api/something', (req, res) => {
        res.json({});
      });
    
      // ...
    
      app.get('*', (req, res) => {
        return nextHandler(req, res);
      });
    
      server.listen(port, (err) => {
        if (err) throw err;
        console.log(`> Ready on http${HTTPS ? 's' : ''}://localhost:${port}`);
      });
    });
    

提交回复
热议问题