很多时候401"未授权&QUOT。在Ajax请求时候、Ajax、QUOT

2023-09-10 18:25:59 作者:一条不归路

我的应用程序页面中的一个被加载通过AJAX的一些内容在我的网页(当前为2的请求,文件准备就绪后)。很多时候,我收到这个Ajax请求与响应的状态为401,未经授权。有时,刷新页面(按F5)是它的工作,有些时候ONY一个请求被接收401状态。少的时候,我收到500(laravel在这种情况下,使用错误的数据库凭据,没有从.ENV)。

谁能帮我解决这个问题?

使用Laravel 5.1.6

感谢

 公共职能手柄($要求,关闭$明年)
{
    如果($这个 - > auth->来宾()){
        如果($请求 - > AJAX()){
            返回响应('擅自',401);
        } 其他 {
            返回重定向() - >客人('auth /中登录');
        }
    }

    返回$下一个($请求);
}
 

解决方案

您可以尝试使用'|| $请求 - > wantsJson()'的,如果检查,如果该请求是阿贾克斯。

 如果($请求 - > AJAX()|| $请求 - > wantsJson()){
        返回响应('擅自',401);
    } 其他 {
        返回重定向() - >客人('auth /中登录');
    }
 
这些考生可申请退费,别错过时间

one of my application page is loading some content via ajax in my page (currently 2 requests, after document ready). Many times I receive for this ajax requests the status "401" with response "Unauthorized.". Sometimes on refresh the page (with F5) is it working, Some times ony one request is receiving 401 status. And less times i receive 500 (laravel is in this case using wrong database credentials, not from .env).

Can anyone help me with this issues?

Using Laravel 5.1.6

Thanks

public function handle($request, Closure $next)
{
    if ($this->auth->guest()) {
        if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect()->guest('auth/login');
        }
    }

    return $next($request);
}

解决方案

You can try using ' || $request->wantsJson() ' with the if for checking if the request is ajax.

if ($request->ajax() || $request->wantsJson()) {
        return response('Unauthorized.', 401);
    } else {
        return redirect()->guest('auth/login');
    }