【问题标题】:Express, how to always serve static directory?Express,如何始终提供静态目录?
【发布时间】:2020-07-20 06:06:02
【问题描述】:

所以我需要 Express 始终提供静态目录。这些是关于如何仅提供 index.html 的大量指南,例如 here。他们使用以下代码:

app.use(express.static(path.join(__dirname, 'build')));

app.get('/*', function (req, res) {
    res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

但是对我来说问题是'/*' 路由只服务于 index.html,而不是它拉入的任何文件,例如 main.js。无论访问者在哪条路径上,我基本上都需要我的应用程序始终提供“build/”服务,因为路由是由前端使用 React Router 处理的。比如:

app.get('/*', function (req, res) {
    res.redirect('/');
});

不起作用,因为它删除了路径。登陆“/aa/bb/cc”的用户应该获得与登陆“/”的用户相同的内容(express.static)。我试过app.use('/*', express.static(...),但是这会导致浏览器中出现SyntaxError: expected expression, got '<',因为似乎每个请求都被路由到静态 index.html 文件?

【问题讨论】:

    标签: javascript node.js express routing


    【解决方案1】:

    不要将它放在 app.get 中,在主 app.js 文件中将它作为 app.use 根据 Express 文档:https://expressjs.com/en/starter/static-files.html

    【讨论】:

      【解决方案2】:

      为了回答我自己的问题,我找到了这个答案:https://stackoverflow.com/a/43373134/11441482

      为了让所有文件都使用绝对路径(例如 src="/main.js"),我必须在前端 Webpack 配置中将 output.publicPath 设置为 '/'。该属性由 html-webpack-plugin 使用。有关详细信息,请参阅此问题:HtmlWebpackPlugin injects relative path files which breaks when loading non-root website paths

      【讨论】:

        猜你喜欢
        • 2014-04-19
        • 1970-01-01
        • 1970-01-01
        • 2017-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多