我对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.
有什么建议怎么办?
如果这只发生在生产中,请务必检查您的nginx配置文件。这可能是由于以下设置:
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
尝试对这些进行评论以查看是否可以解决问题,然后逐个取消评论,并根据需要进行调整。
您可以使用三方来解决此问题:
1)Barvai / Laurwell课程
'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');
}
}