簡體   English   中英

react/axios Auth 和 CORS 問題

[英]react/axios Auth and CORS issue

使用:

背面: 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(未經授權)

Access to XMLHttpRequest at ' http://localhost:8000/api/posts ' from origin ' http://localhost:3000 ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the請求的資源。

如果我添加:

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

Access to XMLHttpRequest at ' http://localhost:8000/api/posts ' from origin ' http://localhost:3000 ' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access -Control-Allow-Origin' header 存在於請求的資源上。

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

那么,我怎樣才能從 Laravel API 和 axios 中的 axios 獲取數據?

更新:

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

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

404(未找到)

我在組上也使用cors ,但仍然相同並且出現 404 錯誤。

為了允許 CORS 我們必須在服務器端和客戶端都啟用請求可能有助於在 axios 中添加請求 header 部分

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM