且构网

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

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

更新时间:2021-07-24 21:41:27

根据 angular.io文档路由的应用必须回退到index.html" .这意味着如果环回无法获取"或导致任何类型的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的路由器可以从那里获取它.

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();
            }
        });
    };
};

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

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 !