Laravel 5.3 Ajax登录 [英] Laravel 5.3 Ajax Login
问题描述
我正在尝试使用带有新Laravel 5.3项目的ajax登录我的用户。
I'm trying to login my users with ajax with a new Laravel 5.3 project.
我已经生成了auth路由,这些路由已添加到我的网站中。 php:
I've generated the auth routes, which got added to my web.php:
Auth::routes();
我有一个带有电子邮件,密码输入和csrf字段的html表单。然后我也有这个javascript文件:
I have a html form with email, and password inputs and the csrf field. Then I also have this javascript file:
$("form.login").submit(function(e) {
e.preventDefault();
$.ajax({
method: "POST",
dataType: "json",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
},
data: $("form.login").serialize(),
url: "/login"
})
.done(function(data) {
console.log(data);
});
});
然而,当我发布时,它显示在我的网络标签中:
When I post it however, this shows up in my network tab:
重定向回原始页面,不返回任何数据。
It redirects back to the original page, without returning any data.
为什么这样做? 5.3不再给json回复吗?
Why is it doing this? Does 5.3 not give json responses anymore?
推荐答案
完整解决方案:
<再来一次,
The Complete Solution:
Hi reinierkors,
我也尝试用5.3版本做同样的事情,我终于解决了它:)解决方案非常干净。
I also tried to do the same with the 5.3 version, I finally solved it :) and the solution is very clean.
首先,我在 App \Http \Controllers \ Api 下创建了一个新文件夹,名为 Auth ,我这样做只是为了为api添加新的auth控制器,所以我可以重写一些函数,然后我复制了auth控制器( LoginController , ForgotPasswordController , RegisterController )到这个新文件夹。
First, I created a new folder under App\Http\Controllers\Api called Auth, I did it just to add new auth controllers for the api so I can rewrite some functions, then I copied the auth controllers (LoginController, ForgotPasswordController, RegisterController) to this new folder.
在LoginController类中:
我重写了正在进行重定向的函数。
In LoginController Class: I rewrited the functions that were making the redirects.
第一个函数:将在
时自动调用验证返回成功。
The first function: will be automatically called when the authentication return success.
第二个函数:当
身份验证返回错误时,将自动调用。
最后一个函数:将在尝试5次登录尝试后,用户已被锁定
。
The last function: will be automatically called when the user has been locked out after trying 5 login attempts.
/**
* Send the response after the user was authenticated.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
protected function sendLoginResponse(Request $request) {
$this->clearLoginAttempts($request);
return response()->json(['SUCCESS' => 'AUTHENTICATED'], 200);
}
/**
* Get the failed login response instance.
*
* @return \Illuminate\Http\Response
*/
protected function sendFailedLoginResponse() {
return response()->json(['ERROR' => 'AUTH_FAILED'], 401);
}
/**
* Error after determining they are locked out.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
protected function sendLockoutResponse(Request $request) {
$seconds = $this->limiter()->availableIn(
$this->throttleKey($request)
);
return response()->json(['ERROR' => 'TOO_MANY_ATTEMPTS', 'WAIT' => $seconds], 401);
}
在RegisterController类中:
我重写了正在进行重定向的函数。
In RegisterController Class: I rewrited the functions that were making the redirects.
在第一个函数中:我修改了验证器响应以返回一个更舒适的响应(数组)来使用。
In the first function: I modified the validator response to return a more comfortable response (array) to work with.
第二个函数:将自动调用注册返回成功。
The second function: will be automatically called when the registration return success.
/**
* Handle a registration request for the application.
*
* @param Request $request
* @return \Illuminate\Http\Response
*/
public function register(Request $request) {
$validator = $this->validator($request->all());
if($validator->fails())
return response()->json(['ERROR' => $validator->errors()->getMessages()], 422);
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
/**
* The user has been registered.
*
* @param Request $request
* @param mixed $user
* @return mixed
*/
protected function registered(Request $request, $user) {
return response()->json(['SUCCESS' => 'AUTHENTICATED']);
}
在ForgotPasswordController类中:
我重写了正在进行重定向的函数。
In ForgotPasswordController Class: I rewrited the function that was making the redirects.
我修改了重置链接电子邮件功能,以便我们可以获得消息并显示为json而不是重定向。
I modified the reset link email function so we can get the messages and display as json instead of the redirects.
/**
* Send a reset link to the given user.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse
*/
public function sendResetLinkEmail(Request $request)
{
$validator = Validator::make($request->only('email'), [
'email' => 'required|email',
]);
if ($validator->fails())
return response()->json(['ERROR' => 'VALID_EMAIL_REQUIRED'], 422);
// We will send the password reset link to this user. Once we have attempted
// to send the link, we will examine the response then see the message we
// need to show to the user. Finally, we'll send out a proper response.
$response = $this->broker()->sendResetLink(
$request->only('email')
);
if ($response === Password::RESET_LINK_SENT) {
return response()->json(['SUCCESS' => 'EMAIL_SENT'], 200);
}
// If an error was returned by the password broker, we will get this message
// translated so we can notify a user of the problem. We'll redirect back
// to where the users came from so they can attempt this process again.
return response()->json(['ERROR' => 'EMAIL_NOT_FOUND'], 401);
}
这篇关于Laravel 5.3 Ajax登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!