koa服务器启用HTTPS与HTTP/2:nodejs启用http2服务
Author:zhoulujun Date:
2023年8月10日更新:
http2 https http 现在是nodejs 内置的了
所以最新的配置如下:
const Koa = require('koa'); const static = require('koa-static'); const { koaBody } = require('koa-body'); const router = require('./src/router/index'); const path = require('path'); const app = new Koa(); const http2 = require('http2'); const http = require('http'); const fs = require('fs'); const { Port } = require('./src/const'); const cors = require('koa2-cors'); // 1.静态资源服务,指定对外提供访问的根目录,不包括 public app.use(static(__dirname + '/public')); // 使用文件上传中间件 app.use(koaBody({ multipart: true, //允许上传文件 formidable: { //这是个 node 包, 设置一下选项 uploadDir: path.join(__dirname, '/public/upload'), //设置上传目录 keepExtensions: true, //设置文件后缀名保留 maxFieldsSize: 1000 * 1024 * 1024, /* onFileBegin:(name,file) => { // 文件上传前的设置 // console.log(`name: ${name}`); // console.log(file); },*/ } })) app.use(cors( { exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'], maxAge: 5, credentials: true, allowMethods: ['GET', 'POST','PUT', 'DELETE'], allowHeaders: ['Content-Type', 'Authorization', 'Accept'], } )) app.use((ctx, next) => { return next().catch((err) => { if (err.status === 401) { ctx.status = 401; ctx.body = 'Protected resource, use Authorization header to get access\n'; } else { throw err; } }); }); router(app); app.use(async (ctx) => { ctx.body = { result: true, data: '后台首页', message: 'ok' }; }); const httpsServer = http2.createSecureServer({ allowHTTP1: true, key: fs.readFileSync(path.join(__dirname, '/ssl/www.demo.cn.key')), cert: fs.readFileSync(path.join(__dirname, '/ssl/www.demo.cn_bundle.crt')), }, app.callback()); httpsServer.listen(443); // const httpServer = http.createServer(app.callback()); // httpServer.listen(80); // app.listen(Port);
chrome现在要求网站都启用https,第二个也是防止网站被劫持。
关于https,推荐参看:
创建一个https服务
const Koa = require('koa'); const https = require('https') const sslify = require('koa-sslify').default app.use(sslify()) const options = { key: fs.readFileSync(__dirname + '/ssl/www.sekocnc.cn.key'), cert: fs.readFileSync(__dirname + '/ssl/www.sekocnc.cn_bundle.pem'), } https.createServer(options, app.callback()).listen(3000, (err) => { if (err) { console.log('服务启动出错', err); } else { // db.connect(); // 数据库连接 console.log('guessWord-server运行在' + Const.Port + '端口'); } });
都启用了https,那么就启用http2呗。关于http2,推荐:
再谈TCP/IP三步握手&四步挥手原理及衍生问题—长文解剖IP
创建一个http2服务
const http2 = require('http2'); const Koa = require('koa'); const app = new Koa(); app.use(async ctx => { ctx.body = 'Hello World'; }); http2.createSecureServer({ key: readFileSync(`${__dirname}/localhost-privkey.pem`), cert: readFileSync(`${__dirname}/localhost-cert.pem`), }, app.callback()).listen(3000);
其他的,可以参看:https://dexecure.com/blog/native-http2-support-node-frameworks-hapi-koa-express/
这个教程写的非常详细
转载本站文章《koa服务器启用HTTPS与HTTP/2:nodejs启用http2服务》,
请注明出处:https://www.zhoulujun.cn/html/webfront/server/koa/8831.html