问题描述
系统信息
- Express: 4.16.4
- NextJS: 8.0.3
- React: 16.8.4
- ReactDOM: 16.8.4
目标
在本地主机上使用 SSL over HTTPS 为 Web 应用程序提供服务
Serve the web application using SSL over HTTPS on localhost
做了什么
- 使用 Create Next App 创建了基本的 NextJS 应用程序
- 使用 OpenSSL 生成证书和密钥并将其移至项目目录中
- 添加了 Express 依赖项
- 将应用配置为在
server.js
中使用 express - 将脚本更改为在
package.json
脚本中使用server.js
.
- Created basic NextJS application using Create Next App
- Generated a certificate and key using OpenSSL and moved it into the project directory
- Added the Express dependency
- Configured the app to use express inside
server.js
- Changed script to use the
server.js
insidepackage.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
初始化时可以运行.我曾尝试使用 this answer 通过 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 在本地主机上进行 HTTPS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!