angular - 尝试调用 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'">
解决方案
所以,起初我为我的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 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'
]
}
};
推荐阅读
- node.js - 在 Heroku 上部署 Node.js 应用程序在本地成功,但显示错误:无法在线找到模块“/app/server”
- python - 将 python 文件导入 Jupyter Notebook
- javascript - 如何在 express.js 中处理具有无限可能性的路线?
- reactjs - 在 React.js 中为 Range Slider 创建 onChange 函数
- sql - sql - 按列排序(该列具有所有空值)
- bootstrap-4 - 如何使引导列可水平滚动
- git - 删除冲突文件后,合并没有实现源分支中的文件进行合并
- c - 如何在 C 中的编译时计算非整数(小数)log2
- python - 如何检查字符串日期格式是否可排序?
- indexing - Sails.js/Redis:如何实现二级索引