Я столкнулся с интересной ошибкой (POST http://127.0.0.1:8000/api/auth/signup 422 (Unprocessable Entity)
при выполнении запроса POST с использованием axios
для сохранения информации о пользователе в моей базе данных.
Я создал конечную точку, используя Laravel (PHP framework) и протестирован с помощью Postman с правильными заголовками и работает нормально, но по какой-то причине часть его внешнего интерфейса поставила меня в тупик и не уверен, что делать, когда я врезался в стену. Что я делаю неправильно? Как я могу сделать это? успешно сохранить информацию о пользователе в БД?
import React, {Component} from 'react';
import axios from "axios";
class Register extends Component {
constructor(props) {
super(props);
this.state = {
username: "",
email: "",
password: ""
};
this.userNameHandler = this.userNameHandler.bind(this);
this.emailHandler = this.emailHandler.bind(this);
this.passwordHandler = this.passwordHandler.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
userNameHandler(e) {
this.setState({
username: e.target.value,
});
console.log(this.state.username);
}
emailHandler(e) {
this.setState({
username: e.target.value,
});
console.log(this.state.email);
}
passwordHandler(e) {
this.setState({
username: e.target.value,
});
console.log(this.state.password);
}
handleSubmit(e) {
e.preventDefault();
const user = {
name: this.state.name,
email: this.state.email,
password: this.state.password
}
JSON.stringify(user);
const headers = {
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
}
this.setState({
username: e.target.value
});
axios.post('http://127.0.0.1:8000/api/auth/signup', user, headers)
.then(response => {
console.log(response);
console.log(response.data);
}).catch(error => {
console.log("AXIOS ERROR!! " + error);
});
}
render() {
return (
<div className="container">
<div id="login-row" className="row justify-content-center align-items-center">
<div id="login-column" className="col-md-6">
<div id="login-box" className="col-md-12">
<form id="login-form" className="form" method="post" onSubmit={this.handleSubmit}>
<div className="form-group">
<label htmlFor="username" className="text-info">Username:</label><br/>
<input type="text" name="username" id="username" className="form-control" onChange={this.userNameHandler}/>
</div>
<div className="form-group">
<label htmlFor="username" className="text-info">Email:</label><br/>
<input type="text" name="username" id="username" className="form-control" onChange={this.emailHandler}/>
</div>
<div className="form-group">
<label htmlFor="password" className="text-info">Password:</label><br/>
<input type="text" name="password" id="password" className="form-control" onChange={this.passwordHandler}/>
</div>
<div className="form-group">
<input type="submit" name="submit" className="btn btn-info btn-md"
value="Submit"/>
</div>
</form>
</div>
</div>
</div>
</div>
);
}
}
export default Register;
Вот мой контроллер:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use App\User;
class AuthController extends Controller
{
/**
* Create user
*
* @param [string] name
* @param [string] email
* @param [string] password
* @param [string] password_confirmation
* @return [string] message
*/
public function signup(Request $request)
{
$request->validate([
'name' => 'required|string',
'email' => 'required|string|email|unique:users',
'password' => 'required|string|confirmed'
]);
$user = new User([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password)
]);
$user->save();
return response()->json([
'message' => 'Successfully created user!'
], 201);
}
/**
* Login user and create token
*
* @param [string] email
* @param [string] password
* @param [boolean] remember_me
* @return [string] access_token
* @return [string] token_type
* @return [string] expires_at
*/
public function login(Request $request)
{
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
'remember_me' => 'boolean'
]);
$credentials = request(['email', 'password']);
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if ($request->remember_me)
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString()
]);
}
/**
* Logout user (Revoke the token)
*
* @return [string] message
*/
public function logout(Request $request)
{
$request->user()->token()->revoke();
return response()->json([
'message' => 'Successfully logged out'
]);
}
/**
* Get the authenticated User
*
* @return [json] user object
*/
public function user(Request $request)
{
return response()->json($request->user());
}
}