Axios CORS/Preflight 调用 Laravel 5.4 API 失败

Axios CORS/Preflight failing with Laravel 5.4 API call

我在使用 Laravel 5.4 和使用 Axios 处理请求的 React 应用程序时遇到问题。

这是我遇到的错误。

这是我对失败的预检响应的请求 headers。

这是预检后失败的请求:

这是我的 Axios 请求配置:

let req = axios({
    method: "GET",
    url: https://api.vendorgraphs.com/{queryStringHere}
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + accessToken
    }
});

需要注意的一件有趣的事情是它使用 HTTPS 协议指定端点。我的应用程序上的类似请求正在按应有的方式运行,但这是唯一失败的请求。是因为使用了查询字符串吗?

请求作为 GET 请求到达 API 端点。我正在使用 Laravel 和 laravel-cors 包来处理我的 cors 请求。

这是我的 CORS 配置:

这是我的 Kernel.php

protected $middleware = [
    \Barryvdh\Cors\HandleCors::class,
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];

和我的 cors.php 在配置文件夹中

return [
    'supportsCredentials' => false,
    'allowedOrigins' => ['*'],
    'allowedHeaders' => ['*'],
    'allowedMethods' => ["GET", "OPTIONS", "POST", "PUT", "PATCH", "DELETE"],
    'exposedHeaders' => [],
    'maxAge' => 0,
];

我可以明显地看到预检在网络选项卡中失败。我不明白的是为什么我收到混合内容错误而不是 405 或其他一些 HTTP 状态代码。当我使用 HTTPS 显式设置 url 时,它说我正在使用 HTTP 协议请求端点,这似乎很奇怪。

我已经坚持这个问题一段时间了,可以对这个问题使用一些见解。 似乎很多人都遇到过 "similar" OPTIONS 预检问题。我做过一些事情,比如创建一个中间件,如果请求的方法是 OPTIONS,它只是 returns 一个 200 HTTP 状态代码。但这也没有用。将请求更改为 Axios 的 OPTIONS 并将 Laravel 上的路由更改为类似:

Route::options("/api/endpoint", controller@method);

也没用。我只是不明白为什么它会重定向到 HTTP 协议并返回混合内容错误,而这似乎与 CORS 无关但预检请求失败,这表明它是 CORS 问题。感谢任何和所有见解。

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ / [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP:X-Forwarded-Proto} ^http$
    RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>

您看到的问题的原因是,服务器本身将 https URL 重定向到 http:

$ curl -I 'https://api.vendorgraphs.com/api/dealershipvendorleads/?id=3,4&startDate=2017-4&endDate=2017-8'

HTTP/1.1 301 Moved Permanently
Content-Type: text/html; charset=iso-8859-1
Date: Wed, 20 Sep 2017 15:33:50 GMT
Location: http://api.vendorgraphs.com/api/dealershipvendorleads?id=3,4&startDate=2017-4&endDate=2017-8
Server: Apache
Connection: keep-alive

注意 301 状态代码,以及 Location header 和 http://api.vendorgraphs.com/…

所以这意味着,如果没有浏览器将其作为混合内容阻止,您无法从安全上下文(https 页面)向 cross-origin 端点发出 cross-origin 请求(如您所见)。

所以这并不是真正的 CORS 问题 — 相反,它纯粹是一个 mixed-content 问题。