我有一个通过快递
配置的babel服务器我希望我的静态文件是静态提供的,因此我添加了以下规则:
app.use('/', express.static('public'));
app.get(/.*\.(png|jpg|js|css)$/, express.static('public'));
但是我还想在刷新/直接链接访问时正确加载页面,所以我添加了以下规则
app.get('/*', function (request, response) { // This wildcard method handles all requests
response.sendFile(path.resolve(__dirname, 'public', 'index.html'))
});
但是,现在在页面加载时,当页面请求我的bundle.js时,服务器正在为它提供index.html文件(即使它被先前的静态文件规则捕获)。我认为是这种情况,因为它以某种方式优先考虑/*
规则。如何消除该规则中的静态文件?
上下文的完整档案:
import express from 'express';
import path from 'path';
import helmet from 'helmet';
import session from 'express-session';
const port = process.env.PORT || 8080;
const app = express();
// we use helmet to disable typically unsafe operations
app.use(helmet());
// COOKIE CONFIGURATION
// we do not use the default session cookie name
// this is done to avoid attackers from fingerprinting the server
// and targetting it accordingly
app.set('trust proxy', 1); // trust first proxy
app.use(session({
secret: 'sercret',
name: 'name' // the name of the sesion ID cookie to set in the response and read from the request
}));
// ROUTE CONFIGURATION
app.use('/', express.static('public'));
app.get(/.*\.(png|jpg|js|css)$/, express.static('public'));
app.get('/*', function (request, response) { // This wildcard method handles all requests
response.sendFile(path.resolve(__dirname, 'public', 'index.html'))
});
app.listen(port, () => {
console.log(`Server is now listening on port ${port}`);
});
答案 0 :(得分:1)
RegExp不是与express和path-to-regexp来源相关的有效路线。并更新' /'路线:
app.use(express.static('public'));