【问题标题】:Cors error with embed React while in development mode在开发模式下嵌入 React 时出现 Cors 错误
【发布时间】: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-OriginContent-Disposition,因为它们是响应标头,而不是请求标头。

标签: reactjs drupal cors craco


【解决方案1】:

还需要在 react 应用上添加 CORS 请求:

craco.config.js 文件中:

  devServer: {
    headers: {
      'Access-Control-Allow-Origin': 'https://drupalsite.ddev.site',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
      'Access-Control-Allow-Headers':
        'X-Requested-With, content-type, Authorization',
      'Access-Control-Allow-Credentials': 'true',
    },

【讨论】:

    猜你喜欢
    • 2012-10-03
    • 1970-01-01
    • 2012-02-27
    • 2021-07-05
    • 2021-12-27
    • 2022-01-06
    • 2011-07-25
    • 2021-03-02
    • 2016-05-22
    相关资源
    最近更新 更多