2017-11-18 18 views
0

I持ってこのようなフォルダ構造と反応するアプリ:私は予め圧縮ファイルを提供する必要が予め圧縮ファイルはExpressで提供することができません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

Expressのミドルウェアは、常にあなたがそれらを追加した順序で呼び出されます。したがって、*.js.gzファイルをロードするには、ミドルウェアを express.staticミドルウェアの上に移動する必要があります。

//... 
//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 Not Modifiedエラーが表示されます。あなたはこれについて何か考えていますか? – ozanilbey

+0

さて、私はそれを解決しました。ここで私の独り言について忘れてください:) – ozanilbey

関連する問題