react / axios Auth和CORS问题

时间:2019-10-15 12:55:42

标签: php reactjs laravel cors axios

使用:

返回:Laravel /护照 正面:ReactJs / Axios

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

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

获取http://localhost:8000/api/posts净值:: ERR_ABORTED 401(未经授权)

     

在以下位置访问XMLHttpRequest   来源“ http://localhost:8000/api/posts”中的“ http://localhost:3000”   已被CORS政策阻止:否'Access-Control-Allow-Origin'   标头出现在请求的资源上。

如果我添加:

 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');
});

但是,如果我从headers中删除axios并将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错误。

1 个答案:

答案 0 :(得分:0)

要允许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,
]);