首页 > 解决方案 > 未经身份验证的 api laravel 子域

问题描述

我有未经身份验证的 ajax api laravel 问题。请帮我

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

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

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

这是错误:CORS 策略已阻止从源“http://seller.localhost”访问“http://localhost/api/v1/verify/telephone/send_code”处的 XMLHttpRequest:对预检请求的响应没有通过访问控制检查:响应中“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'));
}

标签: jquerylaravelapicors

解决方案


如果你切换到一个 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 声明有效,那么这应该有效。


推荐阅读