Expressjs GET 对 javascript 文件的 GET 请求作为文本/html

Sha*_*arZ 4 javascript node.js express web

我有一个主要使用 Angular 的应用程序,我想将它连接到 Express 以加密和发送私有 API 密钥,这样它们就不会简单地存储在客户端上。

我的问题是浏览器将静态提供的 js 文件读取为 text/html,这导致我的 javascript 无法加载。您可以看到响应是 200 并且文件在那里,只是没有被正确解释。
图片

index.html 有很多这样的脚本请求

<script type="text/javascript" src="/keys.js"></script>
<script type="text/javascript" src="/public/lib/underscore/underscore-min.js"></script>
<script type="text/javascript" src="/public/lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript"  src="/public/lib/bootstrap/dist/js/bootstrap.min.js"></script>
...
Run Code Online (Sandbox Code Playgroud)

快速路由代码:

var express = require('express');
var path = require('path');

var app = express();

app.use(express.static(path.resolve('./public')));

app.get('*', function(req,res) {
    res.sendFile(path.resolve('./public/views/index.html'));
});

app.listen(3000);
Run Code Online (Sandbox Code Playgroud)

任何有 Express 经验的人 - 提供具有不同 MIME 类型的静态文件的正确方法是什么?我最终也需要提供 text/css 类型。

Ale*_*lex 5

您已将应用程序配置index.html为针对每个请求返回:

app.get('*', function(req,res) {
    res.sendFile(path.resolve('./public/views/index.html'));
});
Run Code Online (Sandbox Code Playgroud)

所以 express 尽职尽责地做到了这一点,index.html为任何和所有请求提供服务,包括您希望js通过script标签返回文件的请求。例如,对 的请求/public/lib/underscore/underscore-min.js实际上将在 处返回文件/public/views/index.html

一个简单的解决方法是只返回index.html根请求:

app.get('/', function(req,res) {
    res.sendFile(path.resolve('./public/views/index.html'));
});
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您index.html将在根部提供服务,但仍然可以访问您的 javascript 资产,因为您不是index.html为每个请求提供服务。

此外,由于您已经告诉 express 可以在 中找到静态资产/public,因此在请求它们时无需包含该目录。所以,你的script包含应该是这样的:

<script type="text/javascript" src="/lib/underscore/underscore-min.js"></script>
<script type="text/javascript" src="/lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript"  src="/lib/bootstrap/dist/js/bootstrap.min.js"></script>
Run Code Online (Sandbox Code Playgroud)