2017-11-18 71 views
0

我有一個文件夾結構,這樣的應用程序做出反應:預壓縮的gzip壓縮的文件無法通過快遞送達可能是因爲走錯了路

├── index.html 
└── app 
    ├── server.js 
    ├── routes.jsx 
    ├── scripts 
    │ ├── bundle.js 
    │ ├── bundle.js.gz 
    │ ├── vendor.js 
    │ └── vendor.js.gz 
    └── components 
     └── ... 

我要爲預壓縮文件(* .js.gz)時的.js請求的文件,但原來的.js文件被提供,而不是。這可能是因爲錯誤的道路,但我無法弄清楚。

這裏是我的server.js文件:

import React from 'react'; 
import ReactDOMServer from 'react-dom/server'; 
import { StaticRouter } from 'react-router'; 
import http from 'http'; 
import express from 'express'; 
import fs from 'fs'; 
import App from '~/routes.jsx'; 

const index = fs.readFileSync('index.html', 'utf8'); 
const PORT = process.env.PORT || 8000; 

const app = new express(); 
const server = new http.Server(app); 

app.use('/app', express.static('app')); 

app.use((request, response) => { 
    const context = {}; 

    const html = ReactDOMServer.renderToString(
     <StaticRouter location={request.url} context={context}> 
      <App/> 
     </StaticRouter> 
    ); 

    if (context.url) { 
     response.writeHead(301, {Location: context.url}); 
     response.end(); 
    } else { 
     response.write(index.replace(
      /<div id="root"><\/div>/, 
      `<div id="root">${html}</div>` 
     )); 
     response.end(); 
    } 
}); 

app.get('*.js', function (request, response, next) { 
    console.log('js requested'); 
    request.url = request.url + '.gz'; 
    response.set('Content-Encoding', 'gzip'); 
    next(); 
}); 

server.listen(PORT); 
console.log(`\nApplication available at localhost:${PORT}\n`); 

回答

0

中間件在快遞在您添加的順序總是被調用。因此要加載*.js.gz文件,您需要將中間件移動到中間件上方。

//... 
//load this middleware first 
app.get('*.js', function (request, response, next) { 
    console.log('js requested'); 
    request.url = request.url + '.gz'; 
    response.set('Content-Encoding', 'gzip'); 
    next(); 
}); 
//then load the express.static middleware 
app.use('/app', express.static('app')); 
//... 
+0

它工作。非常感謝你。我真的很生氣。 – ozanilbey

+0

文件服務正常,所以你的建議可以工作,但還有另一個問題。我得到304未修改錯誤。你有什麼想法嗎? – ozanilbey

+0

好的,我解決了它。忘記我的獨白:) – ozanilbey