基於node 搭建http2服務

一、準備工做:安裝node
二、安裝http2: npm install http2 -g
安裝完成後,在安裝目錄中appData/Roaming>npm>node_modules>http2>example 找到localhost.key和localhost.crt文件,後面須要用到,這個用於生成證書。(在線證書生成地址:https://csr.chinassl.net/)node

 


三、開始建立http2服務chrome

const PORT = 8088;

//const spdy = require('spdy');--這個暫時不用管,spdy是http2的前身。
const http2=require('http2');
const path = require('path');
const fs = require('fs');
const url = require('url');

var options = {
    key: fs.readFileSync('./localhost.key'), //讀取key
    cert: fs.readFileSync('./localhost.crt') //讀取crt
};

var http2server = http2.createServer(options,function(request, response) {
      response.write("hello world");
});
http2server.listen(8088);

訪問https://localhost:8088npm

 

檢測頁面是否使用http2:瀏覽器

 (function(){
    // 保證這個方法只在支持loadTimes的chrome瀏覽器下執行
    if(window.chrome && typeof chrome.loadTimes === 'function') {
        var loadTimes = window.chrome.loadTimes();
        var spdy = loadTimes.wasFetchedViaSpdy; 
        var info = loadTimes.npnNegotiatedProtocol || loadTimes.connectionInfo;
        // 就以 「h2」做爲判斷標識
        if(spdy && /^h2/i.test(info)) {
            return console.info('本站點使用了HTTP/2');
        }
    }
    console.warn('本站點沒有使用HTTP/2');
})();
相關文章
相關標籤/搜索