0
votes

Problem with authentification between laravel/react, when fetch get, all work:

api.php

Route::group(['middleware' => ['web']], function () {

Route::post('login','Auth\LoginController@login');

});

login.js

   getCookie(name) {
if (!document.cookie) {
  return null;
}

const xsrfCookies = document.cookie.split(';')
  .map(c => c.trim())
  .filter(c => c.startsWith(name + '='));

if (xsrfCookies.length === 0) {
  return null;
}

return decodeURIComponent(xsrfCookies[0].split('=')[1]);
  }
   const csrfToken = this.getCookie('CSRF-TOKEN');
   const headers = new Headers({
     'Content-Type': 'application/json',
     'X-XSRF-TOKEN': csrfToken
   });

   fetch('api/login',
     {
       method: 'POST',
       headers,
       body: JSON.stringify( this.state )
     })
      .then(response=> {
        console.log(response);
        this.setState({err: false});
        this.props.history.push('/') ;

      })
      .catch(error=> {
        console.log(error);
        this.refs.email.value='';
        this.refs.password.value='';
        this.setState({err: true});
      });

what's in console: in console what's in postman: in postman

1
well did you look into the server logs to see whats happening?DZDomi
@DZDomi yup, nothing interestingKsym
there is 100% a log entry in the storage directory for the cause of this 500 exception; a 500 error is not coming out of nowhereDZDomi
@DZDomi local.ERROR: The payload is invalid. {"exception":"[object] (Illuminate\\Contracts\\Encryption\\DecryptException(code: 0): The payload is invalid. at /home/vagrant/code/HW/BEPHP/diploma/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php:191) [stacktrace] can u help how to resolve? oh, and when i changed to axios i had | POST diploma.test/api/login 419 (unknown status) and | Error: Request failed with status code 419 at createError (createError.js?2d83:16) at settle (settle.js?467f:18) at XMLHttpRequest.handleLoad (xhr.js?b50d:77)Ksym
Is the JS in your question taken from different sections of your script as it looks like it should cause a SyntaxError?Rwd

1 Answers

0
votes

A 419 error suggests that the CSRF/XSRF token has not been included correctly in the request.

The CSRF and XSRF token are not the same so that can't be used interchangeably. You can either included the CSRF as a part of the request body / a parameter or your can include the XSRF as a header.

You should be able to get your code working by changing:

const csrfToken = this.getCookie('CSRF-TOKEN');
const headers = new Headers({
  'Content-Type': 'application/json',
  'X-XSRF-TOKEN': csrfToken
});

to

const xsrfToken = this.getCookie('XSRF-TOKEN');
const headers = new Headers({
  'Content-Type': 'application/json',
  'X-XSRF-TOKEN': xsrfToken
});