小智 26
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('hello, http2!');
});
var options = {
key: fs.readFileSync('./example/localhost.key'),
cert: fs.readFileSync('./example/localhost.crt')
};
require('http2').createServer(options, app).listen(8080);
Run Code Online (Sandbox Code Playgroud)
编辑
此代码段取自Github上的对话.
Gaj*_*jus 16
如果您正在使用express@^5和http2@^3.3.4,那么启动服务器的正确方法是:
const http2 = require('http2');
const express = require('express');
const app = express();
// app.use('/', ..);
http2
.raw
.createServer(app)
.listen(8000, (err) => {
if (err) {
throw new Error(err);
}
/* eslint-disable no-console */
console.log('Listening on port: ' + argv.port + '.');
/* eslint-enable no-console */
});
Run Code Online (Sandbox Code Playgroud)
请注意https2.raw.如果要接受TCP连接,则必须执行此操作.
请注意,在撰写本文时(2016 05 06),主流浏览器都没有支持HTTP上的HTTP2.
如果要接受TCP和TLS连接,则需要使用默认createServer方法启动服务器:
const http2 = require('http2');
const express = require('express');
const fs = require('fs');
const app = express();
// app.use('/', ..);
http2
.createServer({
key: fs.readFileSync('./localhost.key'),
cert: fs.readFileSync('./localhost.crt')
}, app)
.listen(8000, (err) => {
if (err) {
throw new Error(err);
}
/* eslint-disable no-console */
console.log('Listening on port: ' + argv.port + '.');
/* eslint-enable no-console */
});
Run Code Online (Sandbox Code Playgroud)
请注意,在撰写本文时,我确实设法制作express和http2工作(请参阅https://github.com/molnarg/node-http2/issues/100#issuecomment-217417055).但是,我设法让http2(和SPDY)使用spdy包工作.
const spdy = require('spdy');
const express = require('express');
const path = require('path');
const fs = require('fs');
const app = express();
app.get('/', (req, res) => {
res.json({foo: 'test'});
});
spdy
.createServer({
key: fs.readFileSync(path.resolve(__dirname, './localhost.key')),
cert: fs.readFileSync(path.resolve(__dirname, './localhost.crt'))
}, app)
.listen(8000, (err) => {
if (err) {
throw new Error(err);
}
/* eslint-disable no-console */
console.log('Listening on port: ' + argv.port + '.');
/* eslint-enable no-console */
});
Run Code Online (Sandbox Code Playgroud)