【问题标题】:Problem with static routing in Node.js using express使用 express 的 Node.js 中的静态路由问题
【发布时间】:2022-01-24 02:11:54
【问题描述】:

我遇到了一些自定义路由代码的问题,一切正常,并且与我所做的客户端视图路由同步,但是一旦我有了子页面,它就无法正确路由我的静态文件.

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

它不会给我根目录中的文件,而是像来自子文件夹一样提供它。

示例:我转到 http://localhost/sign-up,从 /scripts 加载到我的索引文件中的文件已加载,但如果我转到http://localhost/sign-up/2,它会尝试从 /sign-up/scripts

加载脚本
const express = require('express');
const path = require('path');

const app = express();

app.use('/views', express.static(path.resolve(__dirname, 'frontend', 'views')));

app.use('/styles', express.static(path.resolve(__dirname, 'frontend', 'styles')));
app.use('/scripts', express.static(path.resolve(__dirname, 'frontend', 'scripts')));
app.use('/media', express.static(path.resolve(__dirname, 'frontend', 'media')));

app.get('/*', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'frontend', 'newSite.html'));
});

app.listen(process.env.PORT || 1234, () => console.log('Server is now running...'));

为了解决这个问题,我一直在 youtube 上关注 DCODE 提供的这些教程,但我看不出有什么不妥:

https://www.youtube.com/watch?v=6BozpmSjk-Y

https://youtu.be/OstALBk-jTc

【问题讨论】:

  • 可能是文件夹结构问题。您可以在视频中看到同样的错误。
  • 您能详细说明一下吗?在什么时间戳?
  • 您使用什么 srchref 值在注册文件夹中加载资源?它们应该以 / 开头,以使它们相对于站点 root ,例如href="/styles/stylesheet.css",而不是相对于 html 页面的地址 - 如果前导 / 被省略,它们将是。
  • @traktor 这是问题所在,我没有意识到我已经通过不使用“/”使它们相对于当前路径

标签: javascript node.js express single-page-application url-routing


【解决方案1】:

注册文件夹中加载的资源应使用以“/”字符开头的 URL,以使它们相对于站点根目录,例如

src="/scripts/modulefile.js"
href="/css/stylesheet.css"
href="/media/image.png"

而不是相对于注册文件夹的 url - 如果前导 '/' 被省略,它们将是。

【讨论】:

    【解决方案2】:

    您不需要多个路由来提供静态内容,expressstatic 方法可以为您完成此类任务:

    // If your 'public' or 'static' directory is one of root directories
    app.use(express.static(process.cwd() + '/public'));
    
    // so all these requests will be served:
    // -> /public/styles/custom.css
    // -> /public/scripts/pollyfils.js
    // -> /public/media/logo.png
    

    【讨论】:

    • 它不能解释也不能解决问题,当然也不会伤害应用程序。
    • @kmp 如果您有其他更好的解决方案,请用您自己的解决方案回答。如果您有任何建议,我们可以学习
    • 在某些时候将我所有的静态目录放在一个中可能是个好主意,所以谢谢@Heartbit,但目前我会保持原样,因为它让我可以更好地控制我提供的服务和无法访问的服务
    • 你的wlc,这只是你项目文件结构的separation of concern
    猜你喜欢
    • 2019-09-02
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    • 2022-08-22
    • 1970-01-01
    • 2016-07-23
    • 2014-03-04
    • 2015-10-05
    相关资源
    最近更新 更多