使用 NextJS + Express 在本地主机上使用 HTTPS

IT技术 reactjs express https localhost next.js
2021-04-28 12:31:48

系统信息

目标

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

做了什么

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

服务器.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. 我曾尝试使用此答案通过 https 为应用程序提供服务,但我无法弄清楚如何使用 NextJS 将其应用于我当前的设置。

我花了很多时间在网络上研究如何应用这个解决方案,但还没有找到如何实现这个解决方案的方法。

任何帮助是极大的赞赏。

4个回答

你只需要使用modulecreateServer方法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}`);
    })
  });

其他答案似乎只是放弃快递...在服务器代码和证书遇到一些困难后找到了解决方案,因此希望可以为其他人省去麻烦!

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

其次,提供带有下一个 js 和 express 的 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);
});

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

对于下一个带有 https 的服务器,下面的工作对我来说非常好;

使用node js httpsmodule的这个官方文档创建HTTPS服务器

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

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

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