As part of my Laravel project, I have written a simple user registration feature with the following code:
public function register()
{
$this->validate(request(), [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required'
]);
$user = User::create(request(['name', 'email', 'password']));
auth()->login($user);
return [
'status' => true,
'user' => $user
];
}
After that, I am sending the data form Next.Js
:
using axios
:
let config = {
method: 'post',
url: `http://localhost:8000/api/register`,
headers: {
'Content-Type': 'application/json',
},
data: values,
}
axios(config)
.then(json => console.log(json))
Everything works fine, but when I send a used email address, it throws a 422 error code, and axios cannot catch the result.
So, I tried using fetch
:
fetch('http://localhost:8000/api/register', {
method: "post",
mode: 'no-cors',
body: new URLSearchParams(data)
}).then(res => res.json())
.then(json => console.log(json))
This also works, but when using a used email, it sends a 302 error code and redirects to the index /
.