HTTPS on localhost using NextJS + Express

后端 未结 4 1903
灰色年华
灰色年华 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:18

    You just need to use the createServer method of https module.

    const { createServer } = require('https');
    const { parse } = require('url');
    const { readFileSync } = require('fs');
    const next = require('next');
    
    const port = 3000;
    const dev = process.env.NODE_ENV !== 'production';
    const app = next({ dev });
    const handle = app.getRequestHandler();
    
    const httpsOptions = {
      key: readFileSync('./certificates/key.pem'),
      cert: readFileSync('./certificates/cert.pem')
    };
    
    app.prepare()
      .then(() => {
        createServer(httpsOptions, (req, res) => {
          const parsedUrl = parse(req.url, true);
          handle(req, res, parsedUrl);
        }).listen(port, err => {
          if (err) throw err;
          console.log(`> Ready on https://localhost:${port}`);
        })
      });
    

提交回复
热议问题