如何解决与 express 和头盔一起提供的 React 应用程序无法发出 API 请求
我正在使用 express 提供 React 应用程序构建服务。
const root = path.join(__dirname,'build/');
app.use(express.static(root));
app.use((req,res,next) => {
if (req.method === 'GET' && req.accepts('html') && !req.is('json') && !req.path.includes('.')) {
res.sendFile('index.html',{ root });
} else next();
});
一切都按预期进行。但是,一旦我将 helmet
(不是 react-helmet)添加到 express 应用程序,我就会遇到问题(样式和脚本没有加载)。
在搜索了几个资源之后,我想出了一个解决方案来使它工作。
下面的代码显示了我为加载样式和脚本所做的修复。
app.use(helmet());
app.use(helmet.contentSecurityPolicy({
defaultSrc: [
'\'self\'','https://api.domain.tld/*','https://domain.tld',],styleSrc: [
'\'self\'','\'unsafe-inline\'','https://*.googleapis.com',scriptSrc: [
'\'self\'',contentSrc: [
'\'self\'',}));
此外,我还在 INLINE_RUNTIME_CHUNK=false
中包含了 .env file
。
我目前遇到的问题是我对 api.domain.tld
进行的 API 调用不起作用。它被阻止并在 Firefox 上显示以下错误。
内容安全政策:页面的设置阻止加载 https://api.domain.tld/endpoint(“default-src”)中的资源。
拒绝连接到“https://api.domain.tld/endpoint”,因为它违反了以下内容安全策略指令:“default-src 'self'”。请注意,'connect-src' 未明确设置,因此使用 'default-src' 作为后备。
- 请注意,react 应用程序位于
domain.tld
,API 位于api.domain.tld
解决方法
有两个问题:
-
修复一个语法错误:
contentSrc:
->connectSrc:
-
CSP 规范不允许在路径部分使用 *(通配符),因此请修复
'https://api.domain.tld/*
->'https://api.domain.tld/'
。同样在路径部分,您可以使用:
- 文件夹名称:
'https://api.domain.tld/real_path_here/'
(带有尾部斜杠 /) - 将允许指定文件夹和子文件夹中的任何子文件夹和任何文件。 - 文件名:
'https://api.domain.tld/endpoint'
或'https://api.domain.tld/some_path/script.js'
(没有尾部斜杠 /)- 将只允许指定的文件名。
根据 Documentation,您应该在 directives
内指定源
app.use(helmet.contentSecurityPolicy({
useDefaults: false,// you can change it to `true` if you want.
directives:{
defaultSrc: [
'\'self\'','https://api.domain.tld/','https://domain.tld',],styleSrc: [
'\'self\'','\'unsafe-inline\'','https://*.googleapis.com','image-src': [
'\'self\'','data:',scriptSrc: [
'\'self\'','https://api.domain.tld/*',contentSrc: [
'\'self\'',}
}));
更新
要修复图片无法加载的问题,请添加以下内容。
imageSrc: [
'\'self\'',
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。