【问题标题】:Express: server unable to handle refresh when using URL paramExpress:使用 URL 参数时服务器无法处理刷新
【发布时间】:2018-05-09 16:42:11
【问题描述】:

使用 URL 参数时,例如books/1,由于某种原因,快递应用无法找到和服务Index.js

我使用的是绝对路径,但即使我的 express 应用程序在使用参数在 url 处刷新时仍无法找到 Index.js

正如您在屏幕截图中看到的那样,它没有提供Index.js,而是找不到它,而是以Index.js 的形式提供html 文件。

我正在使用catch-all solution,它在用 url 参数刷新之前效果很好:

app.use(express.static(path.resolve(__dirname,  '..', 'build')));
app.get('/*', (req, res) => {
 res.sendFile(path.join(__dirname, '..', 'build', 'index.html'));
});

我什至尝试为/Index.js 设置特定路线,但没有成功。

app.use(express.static(path.resolve(__dirname,  '..', 'build')));
app.get('/Index.js', (req, res) => {
 res.sendFile(path.join(__dirname, '..', 'build', 'Index.js'))
});
app.get('/*', (req, res) => {
 res.sendFile(path.join(__dirname, '..', 'build', 'index.html'));
});

我也尝试过使用serve-static 而不是express.static,但没有帮助。

如果有人有兴趣看看,我已经在repo 中复制了这个问题。

这个项目的前端在reason-react

【问题讨论】:

  • Index.js<script> 标记的src 属性中删除./

标签: javascript node.js express


【解决方案1】:

这可能很简单,但你试过了吗:res.sendFile('../public/index.js', {root: __dirname});

【讨论】:

  • 我刚试了一下,刷新时得到了403 (Forbidden)
  • 您的文件路径是否正确? ../public/index.js,例如你的文件路径可以是../src/index.js
  • 是的,路径是正确的。它实际上是../build/Index.js。我确信这是正确的,因为当页面在参数 url 上刷新时,快递成功地提供了文件 except。那就是路径似乎以某种方式丢失的时候。
【解决方案2】:

在挂载路径“book/Index.js”上服务 Index.js 解决了这个问题。

像这样:

app.use(express.static(path.resolve(__dirname,  '..', 'build')));
app.get('/book/Index.js', (req, res) => {
 res.sendFile(path.join(__dirname, '..', 'build', 'Index.js'));
});
app.get('/*', (req, res) => {
 res.sendFile(path.join(__dirname, '..', 'build', 'index.html'));
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-02
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    相关资源
    最近更新 更多