更新时间:2023-01-08 23:18:57
问题在于,CORS无法以这种方式工作。当浏览器要在API上测试CORS时,它将向其发送OPTIONS请求。该请求应使用CORS标头和http代码 204
进行响应。
Well the problem is that CORS doesn't work this way. When browser wants to test CORS on an API it will send a OPTIONS request to it. This request should respond with the CORS header and a http code 204
.
所以您需要更新nginx配置如下所示。这不是确切的方法,但应该可以帮助您
So you would need to update you nginx config something like below. It is not exact, but should get you going
server {
server_name symfony.dev;
root /var/www/symfony/public;
location / {
# Match host using a hostname if you like
#if ($http_origin ~* (https?://.*\.tarunlalwani\.com(:[0-9]+)?$)) {
# set $cors "1";
#}
set $cors "1";
# OPTIONS indicates a CORS pre-flight request
if ($request_method = 'OPTIONS') {
set $cors "${cors}o";
}
# OPTIONS (pre-flight) request from allowed
# CORS domain. return response directly
if ($cors = "1o") {
add_header 'Access-Control-Allow-Origin' '$http_origin' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Headers' 'Origin,Content-Type,Accept' always;
add_header Content-Length 0;
add_header Content-Type text/plain;
return 204;
}
add_header 'Access-Control-Allow-Headers' 'Content-Type,Authorization,Lang';
#add_header 'Access-Control-Allow-Headers' '*';
add_header 'Access-Control-Allow-Methods' 'POST,GET,PUT,DELETE,OPTIONS';
add_header 'Access-Control-Allow-Origin' '*';
try_files $uri /index.php$is_args$args;
}
location ~* \.(jpg|jpeg|gif|css|png|js|ico|html|eof|woff|ttf)$ {
add_header 'Access-Control-Allow-Headers' 'Content-Type,Authorization,Lang';
#add_header 'Access-Control-Allow-Headers' '*';
add_header 'Access-Control-Allow-Methods' 'POST,GET,PUT,DELETE,OPTIONS';
add_header 'Access-Control-Allow-Origin' '*';
if (-f $request_filename) {
expires 30d;
access_log off;
}
}
location ~ \.php$ {
add_header 'Access-Control-Allow-Headers' 'Content-Type,Authorization,Lang';
#add_header 'Access-Control-Allow-Headers' '*';
add_header 'Access-Control-Allow-Methods' 'POST,GET,PUT,DELETE,OPTIONS';
add_header 'Access-Control-Allow-Origin' '*';
fastcgi_pass php:9000;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
error_log /var/log/nginx/symfony_error.log;
access_log /var/log/nginx/symfony_access.log;
}
我最近使用了类似的配置为grafana启用CORS(Grafana无法通过AJAX进行回复)。所以这也应该对你有用
I recently used a similar config to enable CORS for grafana (No response from Grafana via AJAX). So this should work for you also