Итак, я делаю что-то неортодоксальное, я объединяю Laravel с React.Я и хочу использовать систему Laravel Auth с реагирующим внешним интерфейсом.
Проблема, с которой я сталкиваюсь, заключается в том, что когда я удаляю часть onSubmit и выполняю стандартную отправку формы в функцию входа в систему, она работает безупречно, но когда я делаю это с помощью axios, он на самом деле не регистрирует меня.
Поэтому я настроил такую форму входа (надеюсь, комментарии помогут):
export default class LoginForm extends React.Component
{
constructor(props) {
super(props);
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.form = React.createRef();
this.state = {
disabled: false,
email: '',
password: '',
csrf: document.head.querySelector('meta[name="csrf-token"]').content,
}
}
onChange(event)
{
this.setState({
[event.target.name] : event.target.value
});
}
onSubmit(e) {
e.preventDefault();
//disable the submit button so they can't click more than once
if(this.state.disabled === false){
this.setState({ disabled: true });
//post to the login the request to login
axios.post(
'/api/login',
{
_token: this.state.csrf,
email: this.state.email,
password: this.state.password
}
).then(
(response) =>
{
// The request was made and the server responded with a status code
// that falls inside the 2xx range
// Login Successful
// Since it's successful we should now be logged in and we can go to the home page.
// window.location.href = "/";
// For Debugging purposes we're not going to go home just yet
this.setState({
disabled: false
});
console.log(response);
//our response does come back okay if the email and password is correct
//however they are not logged in at this point and I'm not sure why.
}
).catch(
(error) => {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
// Login Failed
//remove the disabled state so that the user can try logging in again.
this.setState({
disabled: false
});
}
);
}
}
render(){
const token = document.head.querySelector('meta[name="csrf-token"]');
retrun(
<form name="userRegistrationForm" action="/login" method="POST" onSubmit={this.onSubmit} ref={this.form}>
<input type="hidden" name="_token" value={token.content} />
<input type="text" name="email" onChange={this.onChange} maxLength="100" placeholder="Email" required/>
<input type="password" name="password" onChange={this.onChange} maxLength="100" placeholder="Password" required/>
<button label="Sign In" loading={this.state.submitted} disabled={this.state.disabled} className={"w-100"}>
Sign In
</button>
</form>
)
}
}
Это отправляет запрос через axios на мой контроллер входа в систему laravel.
public function LoginSubmit(Request $request)
{
$request->validate([
'email' => 'required|email|between:1,255',
'password' => 'required|between:1,255',
]);
$auth = false;
//get the credentials from the request
$credentials = $request->only('email', 'password');
//attempt auth
if (Auth::attempt($credentials, $request->has('remember'))) {
$auth = true; // Success
}
//if we authed, then login and return
if ($auth == true) {
return $this->sendResponse(true);
} else {
return $this->sendError(false, "No User found for that email or password does not match");
}
}
Теоретически это должно работать, Auth :: try () должен проверить учетные данные и войти в систему пользователя. На самом деле, это работает без нареканийкогда закончите с формой (просто полностью удалив часть onSubmit) Код для входа в форму Laravel практически идентичен, но вместо ответов json я делаю return redirect("/")
, чтобы вернуться домой.
Так что я должен сделать после получения ответа 200 от сервера, чтобы войти в систему пользователя?
Редактировать: Поскольку сайт, который он преобразовал в React, мне нужно, чтобы сайт выполнял традиционную аутентификацию на основе файлов cookie / сессий, поскольку большая часть сайта все еще использует шаблоны блейдов и аутентификацию сессий.