我对Laravel 5.3 CORS有疑问。我在这个问题上搜索了很多,发现很多推荐用于CORS的barryvdh。然而,这没有用,我发现人们提到这可能是由使用tymondesigns jwt-auth模块引起的。有人建议通过设置
来绕过它header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Authorization, Content-Type');
在api.php文件中。这会产生如下响应:
Failed to load https://example.com/api/v1/members/1: Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.
为了解决此问题,我添加了
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT');
以上2行。然而,这给我留下了一个新问题:
PUT https://example.com/api/v1/members/1 403 (Forbidden)
Failed to load https://example.com/api/v1/members/1: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://example.com' is therefore not allowed access. The response had HTTP status code 403.
有任何建议如何解决这个问题?
答案 0 :(得分:0)
如果仅在生产时发生这种情况,请务必检查您的nginx配置文件。这可能是由于以下设置:
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
尝试对这些内容进行评论,看看是否可以解决问题,然后逐个取消评论,并根据需要进行调整。
答案 1 :(得分:0)
您可以使用三向解决此问题:
1)使用barrvay / laravel-cors
'supportsCredentials' => false,
'allowedOrigins' => ['http://localhost:4200'],
'allowedHeaders' => ['Content-Type','Accept','Authorization'],
'allowedMethods' => ['GET','POST','PUT', 'PATCH', 'OPTIONS', 'DELETE'],
'exposedHeaders' => ['Content-Disposition', 'x-total-count', 'x-filename'],
'maxAge' => 0,
'hosts' => ['*'],
2)使用Chrome插件(Moesif CORS)进行localhost
3)构建一个CORS中间件并将所有cors标头推入其中
namespace App\Http\Middleware;
use Closure;
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');
}
}