0

当我向我的Laravel 7.3 Passport API发出以下axios请求时:

let url = 'http://laravel.test/oauth/token'

let params = {
  client_id:  4,
  client_secret: 'FBkMiLI8ecdb4A8OhLRDGS1SasZP5NT7i9Qpp7bP',
  grant_type: 'password',
  username: 'me@home.com',
  password: '1qaz@WSX',
  scope: '*'
}

let headers = {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type'
  }

axios.post(url, params, headers)
.then(response => {
      this.access_token = response['data']['access_token'];
      this.get_users_data()
  })
.catch(response => {
// eslint-disable-next-line
    console.log(response)
});

我在我的 javascript 控制台中收到此错误:

从源“ http://localhost:3000 ”访问“ http://laravel.test/oauth/token ”的 XMLHttpRequest已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:无“访问” -Control-Allow-Origin' 标头存在于请求的资源上。

此外,config/cors.php在 Laravel 7.3 中配置为允许任何内容(默认情况下):

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */

    'paths' => ['api/*'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => false,

];

我的请求有什么问题?

4

2 回答 2

2

这在 AuthServiceProviders.php 文件中对我有用的解决方案中,但在美学上并不正确:添加 api 前缀,这样就可以config/cors完成它的工作,不要忘记添加它use Illuminate\Support\ Facades\Route;

<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Route;
use Laravel\Passport\Passport;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        // 'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();
        Route::prefix('api')->group(function () {
            Passport::routes();
        });
    }
}
于 2020-07-18T22:25:37.440 回答
0

你的要求没有问题。您的 API 资源有一个CORS 策略,该策略限制了哪些域可以访问该资源。您收到的错误是告诉您该资源没有允许从调用域访问的 CORS 标头。

您需要设置 CORS 策略以将您的域列入白名单:http://localhost:3000. 您可能会发现这篇文章在 Laravel 应用程序中处理 CORS很有帮助:

最近我们发布了 laravel-cors。这个包可以为你的 Laravel 应用添加必要的 CORS 头文件。

于 2020-04-02T16:37:28.783 回答