使用NextJS + Express在localhost上进行HTTPS

本杰明汤匙

系统信息

目标

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

做了什么

  1. 使用Create Next App创建基本的NextJS应用程序
  2. 使用OpenSSL生成证书和密钥,并将其移至项目目录
  3. 添加了Express依赖
  4. 将应用程序配置为在内部使用Express server.js
  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我尝试使用此答案通过https服务该应用程序,但无法弄清楚如何使用NextJS将其应用于当前设置。

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

任何帮助是极大的赞赏。

Tibi02

您只需要使用模块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}`);
    })
  });

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

NextJS默认SSR与使用Express

使用 Apollo 在 NextJS 中进行分页

使用WireShark在localhost上进行端口转发捕获

如何使用 Typescript NextJS 代码访问 Express API?

我可以在nextjs中使用multer而不用express吗?

Nextjs + expressjs + Azure Web App:使用 express 进行两因素身份验证('fs' 不能在客户端使用)

传递对象以在Router.push NextJs上进行查询

NextJS-在1页上进行多次提取的动态路由

使用Node.js和Express for Action在Google上进行同步调用?

使用getStaticPaths在localhost上的NextJS和json-server加载缓慢

使用 HTTPS 的 getServerSideProps 中的 nextjs 和 next-auth getSession() 不起作用

我是否需要 Express 才能使用 Nextjs 创建 Web 服务?

使用本地存储进行身份验证检查时,NextJS屏幕闪烁

可以在localhost上进行PHP重定向(使用exit())后检索会话,但在Godaddy服务器上则不能

NextJs 未使用的 Javascript

使用 nextjs 定位粘性

如何使用 npm 并发包同时运行 Nextjs 应用程序和 Express 服务器?

使用express.js在node.js中进行HTTPS POST请求

使用SyncAdapter在Android上进行双向同步

使用python在Android上进行网页抓取

使用Pandas在列上进行多个聚合

Java使用HashMap在ArrayList上进行迭代

使用sed在单行上进行多次替换

使用hciattach在uart上进行蓝牙?

使用 jsonb 在 postgres 上进行 EAV

使用 MultiIndex 在轴上进行基本索引

使用NEST在ElasticSearch上进行批量更新

如何使用 Pandas 在 datetimeindex 上进行连接?

使用WSL在VSCode上进行ESLint