首页 > 解决方案 > 422 Unprocessable Entity (Laravel/React)

问题描述

I'm using Laravel sanctum to use Rest API's for Laravel Token based authentication and when I send the request to server using axios to the '/register' route it returns a 422 error code .

const handleRegister = async (e) => {
    e.preventDefault()

    axios.defaults.withCredentials = true
    axios.get(`${hostName}/sanctum/csrf-cookie`).then((res) => {
      axios
        .post(`${hostName}/register`, {
          name: 'admin',
          email: 'admin@admin.com',
          password: 'user',
        })
        .then((res) => {
          console.log('account created')
          //history.push('/dashboard')
        })
    })
  }

and the Register Controller is by using the laravel ui --auth package and it looks like this

class RegisterController extends Controller
{
    use RegistersUsers;

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

    /**
     * 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, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\Models\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
    }
}

also for more information in my CORS.php i allowed origins and updated the paths

   'paths' => ['api/*', 'sanctum/csrf-cookie', '/login', '/logout', '/register'],
   'supports_credentials' => true,

i managed to create a user with tinker and i can log in and logout but it returns a 422 when i try to register a new user

标签: javascriptphpreactjslaravelaxios

解决方案


422 错误代码通常意味着您的字段无效,在这种情况下,您的验证失败,如果您的表单中没有密码确认字段,则删除验证器的“已确认”部分。


推荐阅读