You are here

Drupal 8 头后端分离解决cors跨域问题

g089h515r806 的头像
Submitted by g089h515r806 on 星期六, 2020-01-18 03:10

作者:亚艾元技术部

与Drupal8整个前后端分离的项目中,我们经常遇到这样的问题:

Access to XMLHttpRequest at 'http://localhost/gdsy/user/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.


如果生成的静态html+js都放在一个域名下面,就不存在这个问题。域名不一样,这个问题由于浏览器的安全限制,就会存在。


cors : 跨域请求的问题。在Drupal8里面,内置支持了这个功能,但是需要我们修改一下配置,修改service.yml文件的配置:


  cors.config:
    enabled: true
    # Specify allowed headers, like 'x-allowed-header'.
    allowedHeaders: ['content-type', 'authorization']
    # Specify allowed request methods, specify ['*'] to allow all possible ones.
    allowedMethods: ['*']
    # Configure requests allowed from specific origins.
    allowedOrigins: ['*']
    # 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: false


论坛: