将请求从环回重写为 angular2(拒绝执行脚本,因为其 MIME 类型 ('text/html') 不可执行) [英] Rewrite requests from loopback to angular2 (Refused to execute script because its MIME type ('text/html') is not executable)

查看:54
本文介绍了将请求从环回重写为 angular2(拒绝执行脚本,因为其 MIME 类型 ('text/html') 不可执行)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用环回作为后端 api,使用 angular2 作为前端.

I am using loopback as a backend api and angular2 as a frontend.

我正在使用环回来为我的 angular2 前端提供服务.

I am using loopback to also serve my angular2 frontend.

这工作正常,但是,一旦我刷新页面,环回不知道如何处理 url,因为这是 angular 的工作,而不是环回.

This works fine, however, once I refresh a page, loopback does not know how to handle the url because this is angular's job, not loopback.

所以我收到这个错误:

我 100% 理解为什么会出现此错误,因为一旦回送加载我的 index.html,就会引导 angular2 并且知道如何处理这些类型的 URL,因为这是在我的 app.routing.ts 文件中指定的.但是,当直接访问这个链接时,angular2 没有被引导,loopback 不知道如何处理这种类型的 URL.

I understand 100% why I get this error, because once loopback loads my index.html, then angular2 is bootstrapped and knows how to handle those type of URLs because this is specified in my app.routing.ts file. However, when this link is directly accessed, angular2 is not bootstrapped and loopback does not know how to handle this type of URL.

所以我在 server.js 的环回代码中添加了代码,以将所有请求重定向到 angular,除了我用于环回的/api.

So I have added code in my loopback code in server.js to redirect all requests to angular except /api that I use for loopback.

代码如下:

var path = require('path');

var ignoredPaths = ['/api'];

app.all('/*', function(req, res, next) {
  //Redirecting to index only the requests that do not start with ignored paths
  if(!startsWith(req.url, ignoredPaths))
    res.sendFile('index.html', { root: path.resolve(__dirname, '..', 'client') });
  else
    next();
});

function startsWith(string, array) {
  for(let i = 0; i < array.length; i++)
    if(string.startsWith(array[i]))
      return true;
  return false;
}

这有效,但是,没有加载 index.html 页面,我收到以下控制台错误:

This works, however, the index.html page is not loaded and I get the following console errors :

Refused to execute script from 

'http://localhost:3000/inline.bundle.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
59074ce…:1 Refused to execute script from 'http://localhost:3000/polyfills.bundle.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
59074ce…:1 Refused to execute script from 'http://localhost:3000/scripts.bundle.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
59074ce…:1 Refused to execute script from 'http://localhost:3000/styles.bundle.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
59074ce…:1 Refused to execute script from 'http://localhost:3000/vendor.bundle.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
59074ce…:1 Refused to execute script from 'http://localhost:3000/main.bundle.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

我明白这个错误,但不知道为什么我会收到这个,也不知道如何解决这个问题.

I understand the error, but dont know why i am receiving this and dont know how to fix this.

这是我的环回后端的 middleware.json 文件:

This is my middleware.json file for my loopback backend:

{
  "initial:before": {
    "loopback#favicon": {}
  },
  "initial": {
    "compression": {},
    "cors": {
      "params": {
        "origin": true,
        "credentials": true,
        "maxAge": 86400
      }
    },
    "helmet#xssFilter": {},
    "helmet#frameguard": {
      "params": [
        "deny"
      ]
    },
    "helmet#hsts": {
      "params": {
        "maxAge": 0,
        "includeSubdomains": true
      }
    },
    "helmet#hidePoweredBy": {},
    "helmet#ieNoOpen": {},
    "helmet#noSniff": {},
    "helmet#noCache": {
      "enabled": false
    }
  },
  "session": {},
  "auth": {},
  "parse": {
    "body-parser#json": {},
    "body-parser#urlencoded": {"params": { "extended": true }}
  },
  "routes": {
    "loopback#rest": {
      "paths": [
        "${restApiRoot}"
      ]
    }
  },
  "files": {
    "loopback#static": {
      "params": "$!../client/"
    }
  },
  "final": {
    "loopback#urlNotFound": {}
  },
  "final:after": {
    "strong-error-handler": {}
  }
}

推荐答案

根据 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 !

这篇关于将请求从环回重写为 angular2(拒绝执行脚本,因为其 MIME 类型 (&amp;#39;text/html&amp;#39;) 不可执行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆