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

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

问题描述

我正在使用Loopback作为后端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不会被引导,并且回送也不知道如何处理这种类型的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的回送代码中添加了代码,以将所有请求重定向到除用于回送的/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" .这意味着如果环回无法获取"或导致任何类型的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 !

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

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