我正在使用 Magento 2 Rest api 开发一个跨平台移动应用程序。我已在我的 apache 服务器中启用了 CORS。
/etc/apache2/sites-available/000-default.conf
<VirtualHost *:80>
# The ServerName directive sets the request scheme, hostname and port that
# the server uses to identify itself. This is used when creating
# redirection URLs. In the context of virtual hosts, the ServerName
# specifies what hostname must appear in the request's Host: header to
# match this virtual host. For the default virtual host (this file) this
# value is not decisive as it is used as a last resort host regardless.
# However, you must set it for any further virtual host explicitly.
#ServerName www.example.com
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the loglevel for particular
# modules, e.g.
#LogLevel info ssl:warn
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
# For most configuration files from conf-available/, which are
# enabled or disabled at a global level, it is possible to
# include a line for only one particular virtual host. For example the
# following line enables the CGI configuration for this host only
# after it has been globally disabled with "a2disconf".
#Include conf-available/serve-cgi-bin.conf
# Always set these headers.
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
# Added a rewrite to respond with a 200 SUCCESS on every OPTIONS request.
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
</VirtualHost>
当我从浏览器调用 api 时。我收到成功响应。
但在我的控制台中显示 CORS 相关问题。
请帮我解决这个问题?
从您的
Header always set Access-Control-Allow-Origin "*"
上移除 000-default.conf
,同时移除 Header always set Access-Control-Allow-Headers
。
这些导致在响应中发送多个
Access-Control-Allow-Origin
和 Access-Control-Allow-Headers
标头。 (请参阅开发工具图像中的响应标头部分。当浏览器看到多个具有相同名称的响应标头时,它们会合并标头的值。)
所以,无论如何,服务器环境的其他部分已经在设置这些标头。您要么需要禁用添加这些内容的其他任何内容,要么只需添加尚未添加的任何其他必要标头。
例如,响应中只有一个
Access-Control-Allow-Headers
,也只有一个 Access-Control-Max-Age
,所以大概您的 Apache 配置是唯一添加这些内容的。