首页 > 解决方案 > Larvel 5.8:从 javascript 但不是从浏览器调用路由时忽略中间件

问题描述

我有一个简单的“cors”中间件

public function handle($request, Closure $next)
{
    // return response()->json(['message' => 'Not Found.'], 404);
    if (config('app.env') !== 'production') {
        return $next($request)
                ->header("Access-Control-Allow-Origin", "*")
                ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    } else  {
        return $next($request);
    }

}

routes/api.php我以这种方式添加了中间件:

<?php

// Rotte /api/v1
Route::group(['prefix' => 'v1', 'middleware' => ['cors'] ], function () {

    ... wrapping all /api/v1 routes

}

当我从浏览器访问网址时,我在开发者选项中看到

在此处输入图像描述

但是,当 javscript 调用相同的 url 时,“选项”预检请求失败

从源“ https://localhost:3000 ”访问“ https://project.local/api/v1/customer ”的 XMLHttpRequest已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否请求的资源上存在“Access-Control-Allow-Origin”标头。

我究竟做错了什么?

请注意,要求 laravel 列出我的路线,实际上表明应用了 cors !

php artisan route:list --path api/v1/
+--------+-----------+-------------------------------+------------------+----------------------------------------------------------+---------------------+
| Domain | Method    | URI                           | Name             | Action                                                   | Middleware          |
+--------+-----------+-------------------------------+------------------+----------------------------------------------------------+---------------------+
|        | GET|HEAD  | api/v1/customer               | customer.index   | App\Http\Controllers\CustomerController@index            | api,cors,jwt.verify |
|        | POST      | api/v1/customer               | customer.store   | App\Http\Controllers\CustomerController@store            | api,cors,jwt.verify |
|        | GET|HEAD  | api/v1/customer/{customer}    | customer.show    | App\Http\Controllers\CustomerController@show             | api,cors,jwt.verify |
|        | PUT|PATCH | api/v1/customer/{customer}    | customer.update  | App\Http\Controllers\CustomerController@update           | api,cors,jwt.verify |
|        | DELETE    | api/v1/customer/{customer}    | customer.destroy | App\Http\Controllers\CustomerController@destroy          | api,cors,jwt.verify |

标签: javascriptlaravelcors

解决方案


请使用其他标头更新您的中间件,

 if (config('app.env') !== 'production') {
        return $next($request)
                ->header("Access-Control-Allow-Origin", "*")
                ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
                ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-XSRF-TOKEN, X-Requested-With');

这应该可以解决问题。


推荐阅读