2017-04-11 202 views
0

我已經做了一個小型服務器嘗試在節點上的http2,但我不知道推機制是否工作。我的風格負荷在http2但是,這並不意味着,推動工作爲目的...快速http 2服務器推送

const port = 3000 
const spdy = require('spdy') 
const express = require('express') 
const path = require('path') 
const fs = require('fs') 
const app = express() 

app.get('*', (req, res) => { 
    res.set('Link', '</css/styles.css>; rel=preload; as=style'); 
    res.sendFile(__dirname + '/index.html') 
}) 

const options = { 
    key: fs.readFileSync(__dirname + '/keys/server.key'), 
    cert: fs.readFileSync(__dirname + '/keys/server.crt') 
} 

spdy.createServer(options, app).listen(3000); 

在devtools,發起者說:「其他」。

+0

嘗試使用[這](https://chrome.google.com/webstore/detail/http2-and-spdy-indicator/mpbpobfflnpcgagjijhmgnchggcjblin)在鉻 藍色表示SPDY,紅色表示HTTP1.1,綠色代表QUIC – alpheus

+0

@alpheus http2正在工作,我可以在devtool網絡協議列中看到。但是沒有提到推動。在你的擴展中也沒有提到它(它對我來說是藍色的btw)。 – Ced

回答

3

您需要明確告訴您的快遞服務器推送哪些資源。在這裏尋找一個體面的運行通過它:

https://webapplog.com/http2-server-push-node-express/

從該頁面的一個例子路線:

app.get('/pushy', (req, res) => { 
    var stream = res.push('/main.js', { 
    status: 200, // optional 
    method: 'GET', // optional 
    request: { 
     accept: '*/*' 
    }, 
    response: { 
     'content-type': 'application/javascript' 
    } 
    }) 
    stream.on('error', function() { 
    }) 
    stream.end('alert("hello from push stream!");') 
    res.end('<script src="/main.js"></script>') 
}) 

調用res.push()在這裏與你要提供服務的文件的關鍵。

他還記錄的方式寫一些中間件來處理推動資產以及:

https://webapplog.com/http2-server-push-express-middleware/

一旦你有了這個實現,你可以在Chrome中看到devtools推送的項目,如從BazzaDP答案。

1

Chrome瀏覽器將顯示「推/其他」在開發的啓動器欄工具 - >網絡如果資產從服務器推送:

enter image description here

我不使用節點的SDPY模塊,但看起來像herehere這個模塊並沒有像其他服務器(例如Apache)那樣使用Link頭來推送資源。所以,除非你有,例如,在HTTP/2模式下的Apache,否則我懷疑你的代碼將推動資源。