首页 > 解决方案 > 尝试调用 API 时出错(内容安全策略)

问题描述

尝试get从已部署的网站启动功能并收到此错误:

Refused to connect to 'https://www.themealdb.com/api/json/v2/xxx/search.php?s=apple' because it violates the following Content Security Policy directive: "default-src 'self' http://*.google-analytics.com http://www.googletagmanager.com https://*.google.com https://*.google-analytics.com https://*.googletagmanager.com https://*.gstatic.com https://*.googleapis.com https://authedmine.com https://az743702.vo.msecnd.net https://sentry.io ws://localhost:4200". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.

在 localhost 服务器上运行网站时,一切正常。

将此添加meta tag到我的index.html并仍然收到相同的错误消息。

<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' http://* 'unsafe-inline'; script-src 'self' http://* 'unsafe-inline' 'unsafe-eval'">

标签: angularapihttprequestcontent-security-policyhttphandler

解决方案


所以,起初我为我的index.html页面添加了元标记,但它没有用。之后,我创建了interceptor, 将标题添加到我的get函数中。有关拦截器的更多信息,您可以在https://angular.io/api/common/http/HttpInterceptor阅读

还是行不通。然后我发现在我的 server.ts 文件中有这些代码行:

app.use(helmet());
app.use(helmet.contentSecurityPolicy({
  directives: AppConfig.cspDirectives
}));

. 更多信息helmethttps ://www.npmjs.com/package/helmet

然后在我的 app.module providers 部分中分配了{provide: APP_CONFIG, useValue: AppConfig}配置。

这是 app.config.ts 文件现在的样子:

import {InjectionToken} from '@angular/core';

export let APP_CONFIG = new InjectionToken('app.config');

export const AppConfig: any = {
  cspDirectives: {
    defaultSrc: [
      '\'self\'',
      'http://*.google-analytics.com',
      'http://www.googletagmanager.com',
      'https://*.google.com',
      'https://*.google-analytics.com',
      'https://*.googletagmanager.com',
      'https://*.gstatic.com',
      'https://*.googleapis.com',
      'https://authedmine.com',
      'https://az743702.vo.msecnd.net',
      'https://sentry.io',
      'https://www.themealdb.com/',
      'ws:<my-webpage-url>',
    ],
    styleSrc: [
      '\'self\'',
      '\'unsafe-inline\'',
      'https://*.googleapis.com'
    ],
    scriptSrc: [
      '\'self\'',
      '\'unsafe-inline\'',
      'http://*.googletagmanager.com',
      'https://*.google-analytics.com'
    ]
  }
};

推荐阅读