繁体   English   中英

无法加载样式和执行脚本Express JS

[英]Unable to load style and execute script Express JS

我有我的GET请求试图使用以下命令在我的route.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

我在这里想念什么?

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM