使用自定义“密码”字段的AJAX登录

时间:2019-07-09 10:54:22

标签: javascript php ajax laravel

我正在尝试通过AJAX POST请求对用户进行身份验证,并传递两个字段:

"email" (required|string|max:255|unique:users)
"password" (required|min:4)

"password"被视为4位数字的个人识别码。

我尝试更新app\Http\Controllers\Auth\Registercontroller.php,将最小长度从6更改为4。

我的ajax请求当前如下所示:

var formData = new FormData();
formData.append('email', emailStr);
formData.append('password', pin);

$.ajax({
        type: "POST",
        url: "/login",
        dataType: 'json',
        contentType: false,
        processData: false,
        data: formData,
        cache: false,
        success: function (response) {

            console.log('success');

        },
        error: function (jqXHR) {
            var response = $.parseJSON(jqXHR.responseText);
            if(response.message) {
                alert(response.message);
            }
        }
});

PHP: app \ Http \ Controllers \ Auth \ Registercontroller.php:

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'email' => 'required|string|max:255|unique:users',
            'password' => 'required|min:4',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {

        return User::create([
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
}

app \ Http \ Controllers \ Auth \ Logincontroller.php:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

use Illuminate\Http\Request;


class LoginController extends Controller
{



    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/profile';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    protected function authenticated(Request $request, $user)
    {
        if ($request->ajax()){

//            $user = auth()->user();
//            $user->update([
//                'last_login_at' => Carbon::now()->toDateTimeString()
//            ]);
//            $user->last_login_at = new DateTime;
//            $user->save();

            return response()->json([
                'auth' => auth()->check(),
                'user' => $user,
                'intended' => $this->redirectPath(),
            ]);

        }
    }

}

我收到500“给定的数据无效。”消息。

2 个答案:

答案 0 :(得分:0)

以html

<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>

在脚本中

$.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });


$.ajax({
        type: "POST",
        url: "/login",
        dataType: 'json',
        contentType: false,
        processData: false,
        data: $('#form_id').serialize(),
        cache: false,
        success: function (response) {

            console.log('success');

        },
        error: function (jqXHR) {
            var response = $.parseJSON(jqXHR.responseText);
            if(response.message) {
                alert(response.message);
            }
        }
});

答案 1 :(得分:0)

尝试使用此Controller代码获取每个输入的更具体的错误消息:

protected function validator(array $data)
{
    // this will return error response when request is invalid
    $this->validate($data, [
        'email' => 'required|string|max:255|unique:users',
        'password' => 'required|min:4',
    ]);

    // this will executed only if the request is valid
    return response()->json([
        'message' => "Data validated!"
    ]);
}

此ajax代码:

var formData = new FormData();
formData.append('email', emailStr);
formData.append('password', pin);

$.ajax({
        type: "POST",
        url: "/login",
        dataType: 'json',
        contentType: false,
        processData: false,
        data: formData,
        cache: false,
        success: function (response) {

            console.log(response.message);

        },
        error: function (jqXHR) {
            console.log(jqXHR.responseJSON);
            console.log(jqXHR.responseJSON.message);
            // this will display errors on each request data
            $.each(jqXHR.responseJSON.errors, function (i, error) {
                console.log(i, " : ", error[0]);
            });
        }
});