1
votes

I have a react native app that posts and gets data from a remote server. In post, i need to include csrf token to avoid token mismatch errors. This is the backend laravel method

//Android Login
    public function androidLogin(){

      return response()->json([
        'name' => 'Android Login',
        'route' => 'androidLogin'
            ]);
    }

This is the react native code(i have stripped out error catching code).

async handleSubmit(){
  var me = this.state.message;
  console.log('this connected',me);

      let response = await fetch('http://not-brusselus.be/androidLogin', {
                              method: 'POST',
                              headers: {
                                'Accept': 'application/json',
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN':'csrf_field()'
                              },
                              body: JSON.stringify({
                                session:{
                                  email: 'chesterfield@gmail.com',
                                  password: '123456',
                                }
                              })
                            });
      //let res = await response.text();
      if (true) {
         console.log(response);
      } else {
          //Handle error
          //let error = res;
          //throw error;
      }

  }

The response shows laravel's token mismatch page. How can i send the csrf token successfully?.

1

1 Answers

3
votes

Hang the CSRF token off of the window as defined in your main laravel layout file:

window.Laravel = {
    csrfToken: '{{csrf_token()}}'
} 

Then just use that in your javascript requests:

...window.Laravel.csrfToken

Edit

To the downvoter: This is literally how Laravel does it out of the box and recommends you do it as well.