【发布时间】:2022-10-23 23:10:41
【问题描述】:
我正在尝试在 Drupal 9.4.x 站点呈现的页面中嵌入一个 React 应用程序。
它在在线服务器上运行良好,带有构建脚本。 但是,如果我尝试使用开发服务器在本地加载页面,则会收到 CORS 错误:
从源“https://drupalsite.ddev.site”访问“http://localhost:9000/react-app.js”处的脚本已被 CORS 策略阻止:没有“Access-Control-Allow-Origin”标头存在于请求的资源上。
理论上,Drupal 后端已为 CORS 正确配置。
service.yml的配置大概是:cors.config: enabled: true # Specify allowed headers, like 'x-allowed-header'. allowedHeaders: [ 'Access-Control-Allow-Origin', 'Accept', 'Content-Disposition', 'Content-Type', 'x-csrf-token', 'content-type', 'content-disposition', 'authorization' ] # Specify allowed request methods, specify ['*'] to allow all possible ones. allowedMethods: [ '*' ] # Configure requests allowed from specific origins. allowedOrigins: [ 'http://localhost', 'http://localhost:9000', 'https:/www.onlinesite.com' ] # Sets the Access-Control-Expose-Headers header. exposedHeaders: false # Sets the Access-Control-Max-Age header. maxAge: false # Sets the Access-Control-Allow-Credentials header. supportsCredentials: true脚本以这种方式嵌入到树枝中:
<link rel="stylesheet" href="http://localhost:9000/style.css"/> <script type="module" src="http://localhost:9000/react-app.js"></script>我需要在 React 上配置一些东西吗? React 应用程序使用 React 17.0.2 和 Craco 6.1.1 完成。
【问题讨论】:
-
你读过错误信息吗?我没有看到
https://drupalsite.ddev.site被列为允许的来源;它应该是。此外,您可以安全地从允许的请求标头列表中删除Access-Control-Allow-Origin和Content-Disposition,因为它们是响应标头,而不是请求标头。