2017-09-18 56 views
0

在我的主页我有一个表单,我只是加载数据,如果用户进行身份验证。发生什么是我通过ajax提交表单,当用户未通过身份验证时,它会在控制台中发出错误。Laravel - 路径::后不要求登录

它应该问问登录,而不是,我不知道为什么。

这是我发送的数据:

var formData = $('#newLetter').serialize(); 
    var url = '/backend/newLetter/'; 
    $.ajax({ 
     url: url, 
     type: 'POST', 
     data: formData, 
     cache: false, 
     //dataType: 'json', 
     success: function (data, textStatus, jqXHR) { 
      if (typeof data.error === 'undefined') { 
       console.log('SUCCESS: ' + data.success); 
       window.location.href = "/backend/user-letter"; 
      } else { 
       console.log('ERRORS: ' + data.error); 
      } 
     }, 
     error: function (jqXHR, textStatus, errorThrown) { 
      // Handle errors here 
      console.log('ERRORS: ' + textStatus); 
     }, 
     complete: function() { 

     } 
    }); 

我的路线:

Auth::routes();  
Route::post('/backend/newLetter', '[email protected]'); 

当用户没有通过验证,它关系到登录,登录过程表单后我想是。

我该怎么做?

谢谢

+0

由于您正在进行ajax调用,所以它不会进入登录页面。如果您停止使用ajax,Laravel会自动处理它。或者你将不得不在'ajax error method'上手动重定向到登录页面。 – Rakib

回答

0

你必须检查,如果你的用户在你的HomeController登录:

if (Auth::check()) { 
    // The user is logged in, return your response... 
}else{ 
    // The user is not, return a json error to handle with JS 
    // Here you can temporary store the request to execute after login 
} 

如果你不需要阿贾克斯,您可以将验证的中间件添加到您的路线,并如果用户未通过身份验证,它将自动重定向到登录。登录后,Laravel自动重定向到初始URL,但我不知道POST请求的行为,如果您希望停止使用Ajax,这可能是一个很好的起点。

0

您需要使用中间件来确保用户已通过身份验证。看起来您已经正确设置了认证系统,现在只需要使用该中间件保护您的路由。该文档解释了如何做到这一点:

Protecting Routes

所以读取,您应该了解后,你的路线声明应该是:

Route::post('/backend/newLetter', '[email protected]')->middleware('auth'); 

做到这一点更常见的方式是使路由组,这样你就不必使用->middleware('auth')每次:

Route::group(['middleware' => 'auth'], function() { 
    // Define protected routes here 
}); 
1

如果您希望将用户重定向到登录页面如果他们没有通过身份验证,首先您需要使用身份验证中间件来保护您的路由。

Route::post('/backend/newLetter', '[email protected]')->middleware('auth'); 

这将导致重定向到http请求的登录页面和ajax请求的401 Unauthenticated错误。在您使用ajax请求时,您将收到401 Unauthenticated错误,因此您需要将用户重定向回登录页面。添加下面的脚本到您的视图来处理它:

$(document).ajaxError(function(event, jqxhr, settings, exception) { 
    if (exception == 'Unauthorized') { 
     window.location = 'http://yourdomain.com/login';    
    } 
}); 

登录后,他们会重定向到他们访问的最后一页。