HTTPS on localhost using NextJS + Express

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

    Below work for me very well for next server with https;

    Using this official documentation of node js https module Creating HTTPS Server

    const { createServer } = require('http')
    const { parse } = require('url')
    const next = require('next')
    const { readFileSync } = require('fs');
    
    const port = parseInt(process.env.PORT, 10) || 3000
    const dev = process.env.NODE_ENV !== 'production'
    const app = next({ dev })
    const handle = app.getRequestHandler()
    
    const httpsOptions = {
        pfx: readFileSync('./certificates/AMB.pfx'),
        passphrase: 'Testabc$'
      };
    
    app.prepare().then(() => {
        createServer(httpsOptions, (req, res) => {    
            const parsedUrl = parse(req.url, true)
            const { pathname, query } = parsedUrl
    
            if (pathname === '/login') {
                app.render(req, res, '/login', query)
            } else {
                handle(req, res, parsedUrl)
            }
        }).listen(port, err => {
            if (err) throw err
            console.log(`> Ready on https://localhost:${port}`)
        })
    })
    

提交回复
热议问题