And*_*ndy 5 nginx cors laravel-5.5
我有位于 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 ^/(.+)/$ /$1 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。
这是我的代码:
配置/cors.php
<?php
return [
    'supportsCredentials' => false,
    'allowedOrigins' => ['http://yourwebsite.com'],
    'allowedHeaders' => ['*'],
    'allowedMethods' => ['*'],
    'exposedHeaders' => [],
    'maxAge' => 0,
];
应用程序/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');
  }
}
应用程序/Http/Kernel.php
protected $routeMiddleware = [
  ...
  'cors' => \Barryvdh\Cors\HandleCors::class
];
最后在你的路线中使用它:
Route::group(['prefix' => 'about', 'middleware' => [ ..., 'cors']],  function(){ 
  ...
});
感谢您的帮助,对于给您带来的不便,我们深表歉意。
| 归档时间: | 
 | 
| 查看次数: | 10284 次 | 
| 最近记录: |