Express可能无法提供预压缩的gzip压缩文件,因为路径错误

时间:2017-11-18 01:25:45

标签: node.js express gzip gz

我有一个React应用程序,其文件夹结构如下:

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

我需要在请求.js文件但是提供原始.js文件时提供预压缩文件(* .js.gz)。这可能是因为错误的路径,但我无法理解。

这是我的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`);

1 个答案:

答案 0 :(得分:1)

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'));
//...