【问题标题】:react/axios Auth and CORS issuereact/axios Auth 和 CORS 问题
【发布时间】:2026-01-05 15:15:03
【问题描述】:

使用:

返回: Laravel/Passport 前面: ReactJs/Axios

我想在我的页面中获取数据,如果我运行:

axios.get('http://localhost:8000/api/posts')
  .then(response => {
    console.log(response.data);
  })
  .catch((error) => {
    console.log('error ' + error);
  });

GET http://localhost:8000/api/posts net::ERR_ABORTED 401(未授权)

访问 XMLHttpRequest 在 'http://localhost:8000/api/posts' 来自原点'http://localhost:3000' 已被 CORS 策略阻止:没有“访问控制允许来源” 请求的资源上存在标头。

如果我添加:

 headers: {
  Authorization: 'Bearer ' + token,
  crossDomain: true,
  'Access-Control-Allow-Origin': '*'
}

从 'http://localhost:8000/api/posts' 访问 XMLHttpRequest 来源 'http://localhost:3000' 已被 CORS 策略阻止: 对预检请求的响应未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。

在 laravel/api.php 中:

Route::middleware('auth:api')->group(function () {
    Route::get('posts', 'PostController@index');
});

AuthServiceProvider.php

    $this->registerPolicies();
    Route::group([ 'middleware' => [ \App\Http\Middleware\CORS::class ]], function() {
        Passport::routes();
    });

RouteServiceProvider.php

$this->mapApiRoutes();

$this->mapWebRoutes();

Route::group([
    'middleware' => ['auth:api', 'cors'],
    'namespace' => $this->namespace,
    'prefix' => 'auth:api',
], function ($router) {
    Route::apiResource('posts','PostController');
});

但是,如果我从 axios 中删除 headers 并将 route 移到护照身份验证之外,它工作正常,我的意思是在组之外这样:

Route::get('posts', array('middleware' => 'cors', 'uses' => 'PostController@index'));

那么,如何在 reactjs 中使用带有 axios 的护照身份验证从 Laravel API 获取数据?

更新:

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

    Route::get('posts', 'PostController@index');
});

404(未找到)

我也在群里用cors,但还是一样,404错误。

【问题讨论】:

  • 您缺少组中的 cors 中间件。
  • @DavinTryon 我在 RouteServiceProvider.phpAuthServiceProvider.php 上添加了 cors 组,没什么不同
  • 在您的中间件中尝试将cors 作为第一个..
  • @Panther 查看我的答案更新
  • 使用类似Route::group([ 'middleware' => ['cors', 'auth:api'],...

标签: php reactjs laravel cors axios


【解决方案1】:

为了允许 CORS,我们必须在服务器端和客户端都启用请求 可能有帮助 在axios中添加请求头部分

headers: {"Access-Control-Allow-Origin": "*"}

对于路线添加

Route::options(
    '/{any:.*}', 
    [
        'middleware' => ['CorsMiddleware'], 
        function (){ 
            return response(['status' => 'success']); 
        }
    ]
);

和 CorsMiddleware.php 会像

<?php 

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Response;

class CorsMiddleware
{
    protected $settings = array(
        'origin' => '*',    // Wide Open!
        'allowMethods' => 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS',
    );

    protected function setOrigin($req, $rsp) {
        $origin = $this->settings['origin'];
        if (is_callable($origin)) {
            // Call origin callback with request origin
            $origin = call_user_func($origin,
                        $req->header("Origin")
                    );
        }
        $rsp->header('Access-Control-Allow-Origin', $origin);
    }

    protected function setExposeHeaders($req, $rsp) {
        if (isset($this->settings['exposeHeaders'])) {
            $exposeHeaders = $this->settings['exposeHeaders'];
            if (is_array($exposeHeaders)) {
                $exposeHeaders = implode(", ", $exposeHeaders);
            }

            $rsp->header('Access-Control-Expose-Headers', $exposeHeaders);
        }
    }

protected function setMaxAge($req, $rsp) {
    if (isset($this->settings['maxAge'])) {
        $rsp->header('Access-Control-Max-Age', $this->settings['maxAge']);
    }
}

protected function setAllowCredentials($req, $rsp) {
    if (isset($this->settings['allowCredentials']) && $this->settings['allowCredentials'] === True) {
        $rsp->header('Access-Control-Allow-Credentials', 'true');
    }
}

protected function setAllowMethods($req, $rsp) {
    if (isset($this->settings['allowMethods'])) {
        $allowMethods = $this->settings['allowMethods'];
        if (is_array($allowMethods)) {
            $allowMethods = implode(", ", $allowMethods);
        }

        $rsp->header('Access-Control-Allow-Methods', $allowMethods);
    }
}

protected function setAllowHeaders($req, $rsp) {
    if (isset($this->settings['allowHeaders'])) {
        $allowHeaders = $this->settings['allowHeaders'];
        if (is_array($allowHeaders)) {
            $allowHeaders = implode(", ", $allowHeaders);
        }
    }
    else {  // Otherwise, use request headers
        $allowHeaders = $req->header("Access-Control-Request-Headers");
    }
    if (isset($allowHeaders)) {
        $rsp->header('Access-Control-Allow-Headers', $allowHeaders);
    }
}

protected function setCorsHeaders($req, $rsp) {
    // http://www.html5rocks.com/static/images/cors_server_flowchart.png
    // Pre-flight
    if ($req->isMethod('OPTIONS')) {
        $this->setOrigin($req, $rsp);
        $this->setMaxAge($req, $rsp);
        $this->setAllowCredentials($req, $rsp);
        $this->setAllowMethods($req, $rsp);
        $this->setAllowHeaders($req, $rsp);
    }
    else {
        $this->setOrigin($req, $rsp);
        $this->setExposeHeaders($req, $rsp);
        $this->setAllowCredentials($req, $rsp);
    }
}
/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
    public function handle($request, Closure $next) {
        if ($request->isMethod('OPTIONS')) {
            $response = new Response("", 200);
        }
        else {
            $response = $next($request);
        }
        $this->setCorsHeaders($request, $response);
        return $response;
    }
}

并确保使用它来工作 CorsMiddleware

$app->routeMiddleware([
    'CorsMiddleware' => App\Http\Middleware\CorsMiddleware::class,
]);

【讨论】: