我尝试使用位于sites/default/services.yml
的YAML文件将CORS标头添加到我的Drupal 8.2实例中但是我无法让Drupal生成必要的标头:
Access-Control-Allow-Origin → *
这是我的sites/default/services.yml
:
# Configure Cross-Site HTTP requests (CORS).
# Read https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
# for more information about the topic in general.
# Note: By default the configuration is disabled.
cors.config:
enabled: true
# Specify allowed headers, like 'x-allowed-header'.
allowedHeaders: []
# 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
有没有人知道我是否需要验证其他内容,或者如何调试.yml文件无效的原因?
注意:我已尝试添加settings.php
:header("Access-Control-Allow-Origin: *");
但这样做有效,但是,这不是推荐的方法,因为8.2具有此特定配置文件。
答案 0 :(得分:1)
这是我的工作services.yml
文件和Drupal 8.3.7的相应JS请求。
cors.config:
enabled: true
# Specify allowed headers, like 'x-allowed-header'.
allowedHeaders: ['x-csrf-token','authorization','content-type','accept','origin','x-requested-with']
# Specify allowed request methods, specify ['*'] to allow all possible ones.
allowedMethods: ['*']
# Configure requests allowed from specific origins.
allowedOrigins: ['http://localhost:3000']
# Sets the Access-Control-Expose-Headers header.
exposedHeaders: true
# Sets the Access-Control-Max-Age header.
maxAge: 1000
# Sets the Access-Control-Allow-Credentials header.
supportsCredentials: false
这是一个快速的开发人员工具控制台提取来验证响应。
function reqListener() {
var data = this.responseText;
console.log(data);
}
function reqError(err) {
console.log('Fetch Error :-S', err);
}
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.onerror = reqError;
oReq.open('get', 'http://blt.dev/session/token', true);
oReq.send();
这会响应匿名用户的相应csrf令牌。
答案 1 :(得分:0)
我的配置无法正常工作,因为我放弃了services.yml文件的pararameters:属性。
确保它以参数开头:
parameters:
# Configure Cross-Site HTTP requests (CORS).
# Read https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
cors.config:
enabled: true
# Specify allowed headers, like 'x-allowed-header'.
allowedHeaders: ['x-csrf-token','authorization','content-type','accept','origin','x-requested-with']
# Specify allowed request methods, specify ['*'] to allow all possible ones.
allowedMethods: ['*']
# Configure requests allowed from specific origins.
allowedOrigins: ['http://localhost:4200']
# 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