尝试从已部署的网站启动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'">
您应检查您的已部署网站正在发送哪些CSP响应标头。添加元标记只能限制CSP的总数。
而且您正在尝试连接到”。如果您的预期URL在CSP中列为白色,但由于某些原因变为空白,则可能是失败的原因。
所以,起初我为index.html
页面添加了元标记,但该标记无效。之后,我创建了interceptor
,以将标题添加到get
函数中。有关拦截器的更多信息,请访问https://angular.io/api/common/http/HttpInterceptor
仍然无法正常工作。然后我发现在server.ts文件中有以下几行代码:
app.use(helmet());
app.use(helmet.contentSecurityPolicy({
directives: AppConfig.cspDirectives
}));
。有关helmet
的更多信息:https://www.npmjs.com/package/helmet
然后在我的app.module提供商部分中,分配了{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'
]
}
};