javascript - 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
解决方案
422 错误代码通常意味着您的字段无效,在这种情况下,您的验证失败,如果您的表单中没有密码确认字段,则删除验证器的“已确认”部分。
推荐阅读
- java - 频繁的“偏移超出范围”消息,消费者遗弃的分区
- java - 从 Google 电子表格获取数据到我的应用程序的代码突然停止工作
- python - 在 Python 中发送发布请求以登录网站所涉及的步骤
- selenium - 我们应该在 @BeforeClass 中使用 assert 还是在 TestNG 中使用 @BeforeTest 注释,这样做是一个好习惯吗?
- java - 如何为 Firebase 数据库异常添加内置类的无参数构造函数?
- java - 事件监听器的控制流
- python-3.x - 用另一个值更新熊猫数据框的正确方法
- java - login RESTFUL api,它在登录成功时返回一个 id
- python - Selenium 超时异常错误
- api-platform.com - 在 api-platform 中重命名自定义操作