使用NextJS + Express在localhost上进行HTTPS [英] HTTPS on localhost using NextJS + Express

查看:795
本文介绍了使用NextJS + Express在localhost上进行HTTPS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

系统信息

  • Express: 4.16.4
  • NextJS: 8.0.3
  • React: 16.8.4
  • ReactDOM: 16.8.4

目标

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

Serve the web application using SSL over HTTPS on localhost

已完成的操作

  1. 使用创建下一个应用
  2. 创建了基本的NextJS应用
  3. 使用OpenSSL生成证书和密钥,并将其移至项目目录
  4. 添加了Express依赖项
  5. 将应用程序配置为在server.js
  6. 中使用Express
  7. 已更改脚本以在package.json脚本中使用server.js.
  1. Created basic NextJS application using Create Next App
  2. Generated a certificate and key using OpenSSL and moved it into the project directory
  3. Added the Express dependency
  4. Configured the app to use express inside server.js
  5. Changed script to use the server.js inside package.json scripts.

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初始化时,该应用程序当前可以运行.我尝试使用此答案通过https服务该应用程序,但是我无法弄清楚如何将其应用于当前应用使用NextJS进行设置.

The app currently works when initialized using yarn dev. I have tried to serve the app over https using this answer but I was unable to figure out how to apply this to my current setup using NextJS.

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

I spent a lot of time researching the web how to apply this solution but have not yet found a way on how to make this work.

非常感谢您的帮助.

推荐答案

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

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

这篇关于使用NextJS + Express在localhost上进行HTTPS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆