(Laravel & Nginx) CORS header 'Access-Control-Allow-Origin' 不匹配 '(null)'

(Laravel & Nginx) CORS header ‘Access-Control-Allow-Origin’ does not match ‘(null)’

我有位于 localhost:8080 的 SPA 和位于 dev.mywebsite 的 API,两者都在本地服务器上 运行。我尝试使用 ajax 但它返回 'Access-Control-Allow-Origin' 两次,附上截图。我不知道为什么会这样。

下面是我的nginx配置:

# Default server configuration
#
server {
    # Port
    listen 80;
    listen [::]:80;

    # Server Name
    server_name dev.narpandi;

    # Logging
    rewrite_log on;

    # Location of public directory
    root /var/www/personal-website/public;

    # Add index.php to the list if you are using PHP
    index index.php index.html index.htm index.nginx-debian.html;


    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
      try_files $uri $uri/ /index.php?$query_string;
        }

    # Remove trailing slash to please routing system
    if (!-d $request_filename) {
      rewrite ^/(.+)/$ / permanent;
    }

    location ~* \.php$ {
      fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
      fastcgi_index index.php;
      fastcgi_split_path_info ^(.+\.php)(.*)$;
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
      include /etc/nginx/fastcgi_params;

          set $cors "";

          if ($http_origin ~* 'http://localhost:8080')
          {
            set $cors "true";
          }

          if ($cors = 'true')
          {
            add_header 'Access-Control-Allow-Origin' "$http_origin";
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,Pragma,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With';
          }

          #if ($request_method = 'OPTIONS')
          #{
            #return 204;
          #}
    }

    # Disable all htaccess
    location ~ /\.ht {
      deny all;
    }
}

我错过了什么吗?感谢您的帮助。

-已编辑-

决定删除 Nginx CORS 配置并使用 barryvdh/laravel-cors 因为您可以通过添加中间件来指定哪些路由具有 CORS。

这是我的代码:

config/cors.php

<?php

return [
    'supportsCredentials' => false,
    'allowedOrigins' => ['http://yourwebsite.com'],
    'allowedHeaders' => ['*'],
    'allowedMethods' => ['*'],
    'exposedHeaders' => [],
    'maxAge' => 0,
];

app/Http/Middleware/Cors.php

<?php

namespace App\Http\Middleware;

class Cors
{
  public function handle($request, Closure $next)
  {
    return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  }
}

app/Http/Kernel.php

protected $routeMiddleware = [
  ...
  'cors' => \Barryvdh\Cors\HandleCors::class
];

最后在你的路线中使用它:

Route::group(['prefix' => 'about', 'middleware' => [ ..., 'cors']],  function(){ 
  ...
});

感谢您的帮助,对于给您带来的不便,我们深表歉意。

问题是您的应用程序也在设置 CORS header。你需要消除一个。

Nginx 将重复的 header 合并为一个 header,用逗号分隔。这就是你得到的,这是 Nginx 的正常行为。

您正在使用 NGINX cors 和 barryvdh/laravel-cors。两者都创建了 header.

删除 NGINX 一个应该有效。