【问题标题】:Unauthenticated api laravel subdomain未经身份验证的 api laravel 子域
【发布时间】:2020-11-15 12:50:39
【问题描述】:

我遇到 ajax api laravel 问题未经身份验证。请帮帮我

Api: http://localhost/api/v1/verify/telephone/send_code -> 错误

Api:http://seller.localhost/api/v1verify/telephone/send_code -> 好的

网页浏览:http://seller.localhost

这是错误:访问 XMLHttpRequest 在 来自来源的“http://localhost/api/v1/verify/telephone/send_code” “http://seller.localhost”已被 CORS 策略阻止:响应 预检请求未通过访问控制检查: 响应中的“Access-Control-Allow-Credentials”标头是“” 当请求的凭据模式为“包含”时,必须为“真”。这 XMLHttpRequest 发起的请求的凭证模式是 由 withCredentials 属性控制。

这是我在 Seller.localhost 中的代码:

         $.ajaxSetup({
              headers: {
                'Accept': 'application/json',
                'X-CSRF-TOKEN': crsf_token,
                'X-Requested-With': 'XMLHttpRequest'
                },
          });
            
              $.ajax({
                url: 'http://localhost/api/v1/verify/telephone/send_code',
                type: 'post',
                dataType: 'json',
                data: {telephone: $('input[name="telephone"]').val()},
                xhrFields: {
                    withCredentials: true
                },
                crossDomain:true,
                success: function () {
                }
             });

这是 cors 集标题

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods','*')
            ->header('Access-Control-Allow-Credentials', 'true')
            ->header('Access-Control-Allow-Headers', 'Accept, Content-Type, X-CSRF-Token');

    }
}

内核中的中间件cors

    protected $middleware = [
        ....
        \App\Http\Middleware\Cors::class
    ];
  protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
    ],

    'api' => [
        'throttle:60,1',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];

API 路线

 protected function mapApiRoutes()
{
    Route::prefix('api')
        ->middleware('api')
        ->namespace($this->namespace)
        ->group(base_path('routes/api.php'));
}

【问题讨论】:

  • 我最近遇到了类似的问题,发现从 Ajax 切换到 Fetch 可以解决这个问题 (developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) 您是否也尝试过在 htaccess 中设置 CORS 标头值?
  • 不,我在 php 标头中设置了 cors 值。
  • 我会将 Ajax 切换为 fetch 函数,因为这应该可以解决它。我会用一个例子添加一个答案
  • 你在用fruitcake/laravel-cors这个包吗?
  • 没有我使用类 Cors 中间件 return $next($request) ->header('Access-Control-Allow-Origin', '') ->header('Access-Control- Allow-Methods','') ->header('Access-Control-Allow-Credentials', 'true') ->header('Access-Control-Allow-Headers', 'Accept, Content-Type , X-CSRF-Token');

标签: jquery laravel api cors


【解决方案1】:

如果你切换到 fetch 函数,你可以调用 getJSON() 函数而不是你的 $.ajax 调用

async function getJSON() {
    // Get data to send
    var formData = new FormData();
    formData.append('telephone', $('input[name="telephone"]').val());

    // Set the fetch options
    const options = {
        method: 'POST',
        body: formData
    }

    // Get the data
    const response = await fetch('http://localhost/api/v1/verify/telephone/send_code', options)
        .catch(error => {
            alert('Issue: ' + error);
        });

    // Get the JSON response
    const json = await response.json();

    console.log(json);
}

如果您的 CORS 声明有效,那么这应该有效。

【讨论】:

  • 我尝试过但不攻击cookie来验证身份
  • 响应 {消息:“未验证。”} 消息:“未验证。”
猜你喜欢
  • 2019-06-14
  • 1970-01-01
  • 2021-12-20
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 2019-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多