【发布时间】: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 -> 好的
这是错误:访问 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');