且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将请求从环回重写为 angular2(拒绝执行脚本,因为其 MIME 类型 ('text/html') 不可执行)

更新时间:2021-11-08 22:15:40

根据 angular.io 文档路由应用必须回退到 index.html".这意味着如果环回无法GET"或导致任何类型的 404,则表示环回不理解该 url,它需要回退"到 angular2 或 angular4 应用的 index.html.

According to angular.io docs, "Routed apps must fallback to index.html". This means that if loopback cannot "GET" or result in any type of 404, it means that loopback does not understand the url and it needs to "fallback" to the index.html of the angular2 or angular4 app.

要解决此问题,您必须添加自定义中间件以将回送重定向到您的 angular 索引,以便 angular 的路由器可以从那里获取它.

To fix this, you will have to add custom middleware to redirect loopback to your angular index so that angular's router can take it from there.

因此在您的 middleware.json 文件中,更改以下内容:

So in your middleware.json file, change the following :

"final": {
    "./middleware/custom404": {}
    }

然后在/server/middleware/中添加一个文件 custom404.js 使完整路径为 /server/middleware/custom404.js .如果中间件目录不存在,则创建它.

Then add a file custom404.js inside /server/middleware/ so that the full path is /server/middleware/custom404.js . If the middleware directory does not exist, create it.

然后在 custom404.js 文件中:

'use strict';
module.exports = function () {
    var path = require('path');
    return function urlNotFound(req, res, next) {
        let angular_index = path.resolve('client/index.html');
        res.sendFile(angular_index, function (err) {
            if (err) {
                console.error(err);
                res.status(err.status).end();
            }
        });
    };
};

这将重定向回您的 angular 应用程序,并且 angular 的路由器将正确路由 url,同时仍由环回提供服务.

This will redirect back to your angular app and angular's router will route the url correctly while still being served by loopback.

因此不再需要通过 server.js 重定向应用程序,就像我在上面的开头问题中尝试做的那样!

It is therefore no longer needed to redirect the app via server.js as I tried to do in the opening question above !