Safari:“因为请求是跨域请求,所以阻止https:// ...要求其提供凭据。” 更新到Angular 8之后

Mar*_*kus 4 safari basic-authentication angular

我们已经通过基本身份验证保护了Angular网络应用。后更新我们的应用程序从7角到8.0,我们不再要求在Safari浏览器证书和下面的错误出现在控制台:

[Error] Blocked https://*/runtime-es2015.4f263ec725bc7710f1f5.js from asking for credentials because it is a cross-origin request.
[Error] Blocked https://*/main-es2015.6fa442dd5c5a204f47da.js from asking for credentials because it is a cross-origin request.
[Error] Blocked https://*/polyfills-es2015.fd951ae1d7572efa3bc6.js from asking for credentials because it is a cross-origin request.
Run Code Online (Sandbox Code Playgroud)

在Firefox和Chrome中,该应用仍然可以正常运行。Safari版本为12.1.1。

有谁知道Safari存在什么问题?

小智 21

由于 angular/cli 8.1 (PR) 有一个选项crossOrigin用于 ng build 命令(文档)。可能的值为:none | 匿名 | 使用凭证(默认为无)。

使用此选项将更改 index.html 中的脚本标签以添加 crossorigin 属性。

您可以使用此临时文件进行构建: ng build --crossOrigin=anonymous

或者使用 angular.json 中的 Architect.build.options 下的选项:

"architect": {
    "build": {
      "builder": "@angular-devkit/build-angular:browser",
      "options": {
        "crossOrigin": "anonymous", // <-- set value here
        // other options
Run Code Online (Sandbox Code Playgroud)

  • 这应该标记为答案。我还想知道为什么这是 Safari 的问题,而不是其他浏览器的问题。 (7认同)

Dav*_*vid 6

似乎尚未在Safari中实现模块脚本规范(https://github.com/whatwg/html/pull/3656)的某些更改。对我来说,它可以在Safari Technology Preview中使用。

同时,您可以通过crossorigin在模块脚本上添加属性来修复它,如下所示:

<script src="runtime-es2015.ff56c41ec157e6d9b0c8.js" type="module" crossorigin></script>
Run Code Online (Sandbox Code Playgroud)

这是我采用的解决方案(需要一个第三方软件包)。

首先,安装此自定义Webpack构建器@angular-builders/custom-webpack

npm i -D @angular-builders/custom-webpack
Run Code Online (Sandbox Code Playgroud)

确保检查其自述文件中的先决条件,并根据需要更新其他依赖项。

更新您的代码angular.json以使用构建器并设置以下indexTransform选项:

"projects": {
  ...
  "your-app": {
    ...
    "architect": {
      ...
      "build": {
        "builder": "@angular-builders/custom-webpack:browser"
        "options": {
            "indexTransform": "./index-html-transform.js"
              ...
        }
Run Code Online (Sandbox Code Playgroud)

最后,index-html-transform.js在项目的根目录中创建一个文件,其内容如下:

module.exports = (targetOptions, indexHtml) => {
  const regex = /(<script.*?type="module".*?)>/gim;
  return indexHtml.replace(regex, "$1 crossorigin>");
};
Run Code Online (Sandbox Code Playgroud)

现在,当您构建应用程序并index.html发出时,它将自动将该crossorigin属性添加到每个模块脚本中。


小智 6

我的解决方案是--subresource-integrity在构建时添加标志:

ng build --subresource-integrity
Run Code Online (Sandbox Code Playgroud)

此标志还crossorigin根据此注释向模块脚本添加属性。