react next.js 服务端渲染项目引入 https

777 阅读1分钟

从部署一个 HTTPS 服务器开始

开发环境下,可以使用自己的服务器和证书来尝试配置 https 服务。如果你没有自己的服务器和证书,你可以在本地生成一个自签名证书。

以下是使用 OpenSSL 生成自签名证书的步骤:

  1. 安装 OpenSSL(一般Linux系统和MAC系统都自带了)。
  2. 打开终端并导航到要保存证书的目录。
  3. 运行以下命令以生成私钥:openssl genrsa -out server.key 2048。
  4. 运行以下命令以生成证书请求:openssl req -new -key server.key -out server.csr。
  5. 运行以下命令以生成自签名证书:openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt。

Node.js 部署

如果你已经生成了自签名证书,就可以使用 Node.js 的 https 模块在本地部署一个 HTTPS 站点。以下是一个使用自签名证书的示例。

  1. 在 script.js 文件中添加下面代码:

const https = require('https');
const fs = require('fs');
const dev = process.env.NODE_ENV === 'development';
const isHttps = process.env.server_type === 'https' && dev;
const server = express();

const httpServer = isHttps
    ? https.createServer({
        key: fs.readFileSync('./bin/cert/server.key', 'utf8'),
        cert: fs.readFileSync('./bin/cert/server.crt', 'utf8')
    }, server)
    : server;
    //项目中用到了很多第三方的库,这些库在生产环境使用的时候的都会发送https的请求出去,但是再发送请求的时候nodejs会验证证书,没有证书的时候都会无法通过,这里可以修改代码进行修改这个问题
    if (dev&&isHttps) {
        process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
    }
        
 httpServer.listen(port, (err) => {
    if (err) {
        throw err;
    }
    console.log(`> Ready on http://localhost:${port}`);
});

package.json 文件新增配置:

关于接口api 的文件也需要添加相应的更改:

image.png

package.json 文件新增配置:

"dev:https": "cross-env NODE_ENV=development server_type=https sh bin/dev.sh",

image.png

执行 npm run dev:https 来启动项目