Angular 中的 MIME 类型问题

MIME type issue in Angular

当我尝试加载我的主页时出现以下错误,但页面是空白的。

main-es2015.5ff489631e1a2300adb7.js:1 Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

runtime-es2015.2c9dcf60c8e0a8889c30.js:1 Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

vendor-es2015.02ac05cd7eee1cf62f5a.js:1 Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

这之前工作正常,并且在使用 ng serve 服务时在开发中正常工作。当代码是来自服务器的 运行 时会发生此问题。当我从 devtools 检查时,它显示 content-typetext/html 而不是 application/javascript。如何解决这个问题?需要从服务器设置一些东西吗?

angular 路由到您域的根目录。 部署到子文件夹可能会正确引用:

ng build --prod --base-href yoursubfolder

经过长时间的搜索,这对我有帮助。 Ang9 在 index.html 的标签中不包含 MIME 类型:

如果在 tsconfig.json: "target": "es2015" 然后添加 type="module"

<script src="runtime-es2015.703a23e48ad83c851e49.js" type="module">`

或者如果“目标”:“es5”添加nomodule

<script src="runtime-es5.465c2333d355155ec5f3.js" nomodule>

“服务器以非JavaScript MIME 类型响应“text/html” 这个问题只不过是找不到文件。

当我们尝试通过以下代码使用 Express NodeJS 服务 angular 构建应用程序时会发生这种情况

const app = express();
app.use(express.static(__dirname + 'dist/application'));

app.get('/*', function(req, res) {
    res.sendFile(path.join(__dirname + '/dist/application/index.html'));
});

app.listen(process.env.PORT || 8880);

当 Angular 尝试访问某些未找到的文件时会出现此问题

问题已通过以下 Express 代码解决

const _port = 4100;
const _app_folder = 'dist/application';
const app = express();

// ---- SERVE STATIC FILES ---- //
app.get('*.*', express.static(_app_folder, {maxAge: '1y'}));

// ---- SERVE APLICATION PATHS ---- //
app.all('*', function (req, res) {
    res.status(200).sendFile(`/`, {root: _app_folder});
});

// ---- START UP THE NODE SERVER  ----
app.listen(_port, function () {
    console.log("Node Express server for " + app.name + " listening on http://localhost:" + _port);
});

这应该可以解决您的问题。