使用NextJS + Express在localhost上进行HTTPS

时间:2019-03-22 16:35:19

标签: reactjs express https localhost next.js

系统信息

目标

在本地主机上通过HTTPS使用SSL服务Web应用程序

已完成的操作

  1. 使用ReactDOM创建的基本NextJS应用程序
  2. 使用OpenSSL生成证书和密钥,并将其移至项目目录
  3. 添加了Express依赖项
  4. 将应用程序配置为在server.js内使用Express
  5. 已更改脚本以在server.js脚本中使用package.json

server.js

const express = require('express');
const next = require('next');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
const port = 3000;

const https = require('https');
const fs = require('fs');
const httpsOptions = {
  key: fs.readFileSync('./certificates/key.pem'),
  cert: fs.readFileSync('./certificates/cert.pem')
};

app
  .prepare()
  .then(() => {
    const server = express();

    server.get('*', (req, res) => {
      return handle(req, res);
    });

    server.listen(port, err => {
      if (err) throw err;
      console.log('> Ready on http://localhost: ' + port);
    });
  })
  .catch(ex => {
    console.error(ex.stack);
    process.exit(1);
  });

其他信息

使用yarn dev初始化时,该应用程序当前可以运行。我曾尝试使用Create Next App通过https服务该应用程序,但无法弄清楚如何使用NextJS将其应用到当前设置中。

我花了很多时间研究网络上如何应用此解决方案,但尚未找到实现此工作的方法。

非常感谢您的帮助。

4 个答案:

答案 0 :(得分:5)

其他答案似乎只是快速表达...在服务器代码和证书都遇到一些困难之后找到了解决方案,希望可以省去其他人的麻烦!

首先,在此处创建本地证书的可靠建议: https://letsencrypt.org/docs/certificates-for-localhost/

第二,简单的代码提供带有下一个js的HTTP / HTTPS并表达:

const next = require('next');
const express = require('express');
const http = require('http');
const https = require('https');
const fs = require('fs');

const ports = {
  http: 3080,
  https: 3443
}
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
const server = express();  

const options = { 
  key: fs.readFileSync('localhost.key'),
  cert: fs.readFileSync('localhost.crt'), 
};

app.prepare().then(() => {           
  server.all('*', (req, res) => {
    return handle(req, res)    
  });
  http.createServer(server).listen(ports.http);
  https.createServer(options, server).listen(ports.https);
});

值得注意的是,一个端口可以省略或重定向。

答案 1 :(得分:4)

您只需要使用createServer模块的https方法。

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}`);
    })
  });

答案 2 :(得分:0)

对于使用https的下一台服务器,我的工作非常顺利;

使用node js https模块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}`)
    })
})

答案 3 :(得分:0)

我们简单,可切换的实现:

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}`);
  });
});