【问题标题】:Unable to load style and execute script Express JS无法加载样式和执行脚本 Express JS
【发布时间】:2018-09-01 03:30:54
【问题描述】:

我的 GET 请求试图在我的 routes.js 文件中加载一个 html 页面

  app.get('/api/testresult', (req, res) => {
    res.sendFile('/path/myfile.html');
  });

另外,在我的 server.js 中,我有以下内容

const express        = require('express');
const bodyParser     = require('body-parser');
const app            = express();
const path = require('path');

const port = 8000;

app.use('/', express.static(path.join(__dirname, './app/report')));
require('./app/routes')(app, {});
app.listen(port, () => {
  console.log('Server running on ' + port);
});

但是,当我尝试进行 GET 调用时,它会在浏览器控制台上引发错误

localhost/:1 Refused to apply style from
'http://localhost:8000/api/testresult/assets/app.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
localhost/:2 GET http://localhost:8000/api/testresult/assets/app.js 404 (Not Found)
localhost/:1 Refused to execute script from 'http://localhost:8000/api/testresult/assets/app.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

我的文件结构是

MyApp 
app 
 —report 
      —assets 
        —app.css
        —app.js
     —my file.html
 —routes
    —index.js
    —routes.js
node_modules
package.json
server.js

我在这里错过了什么?

【问题讨论】:

  • 那么,对于这个错误GET http://localhost:8000/api/testresult/assets/app.js 404 (Not Found)app.js 在您的文件系统中的位置是什么?
  • 如果您试图显示文件层次结构,我们无法在 cmets 中真正读取它。请使用“编辑”链接将该信息添加到问题的末尾,以便您可以适当地对其进行格式化。
  • 是的,这很难。在 cmets 中添加了

标签: javascript html express


【解决方案1】:

因此,您的目录层次结构在 /assets/app.js 处显示 app.js,从您指向 express.static() 中间件的位置。因此,这就是您需要使用它来提供该文件的 URL,但您显然使用的是路径为 /api/testresult/assets/app.js 的 URL。那些根本不匹配。该 URL 将在:

app/report/api/testresult/assets/app.js

但是,这不是文件所在的位置(因此您会得到 404)。

您可以通过以下几种方式修复它:

  1. 将客户端 URL 更改为 "/assets/app.js"。我猜你可能在你的客户端文件中指定了"assets/app.js"。由于这是一个相对 URL,因此浏览器会将其与您的网页路径结合起来,以构建您的服务器收到的对 /api/testresult/assets/app.js 的请求的 URL。
  2. 更改 express.static 行以包含正确的路径前缀 app.use('/api/testresult', express.static(path.join(__dirname, './app/report')));

【讨论】:

  • 假设我正在尝试从 MyApp 之外的另一个位置呈现 html 文件,我应该如何进行这项工作?当我在 MyApp 中有文件夹时,我得到了你的解决方案。但我无法从外面让它工作。我尝试将整个外部路径添加到 app.use('path', express.static('path')) 但我不会工作
  • @kandarpgandhi - 我不明白那个评论是什么意思。也许您想写一个新问题并显示您要问的确切细节。呈现的 HTML 文件在文件系统中的位置与 HTML 中的路径如何工作无关 - 它们是完全独立的事物,由您定义路由的方式以及在 HTML 中指定 URL 的方式控制。
  • @kandarpgandhi - 我在那里提供了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-28
  • 2011-09-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多