在来自本机应用程序的发布请求中包含csrf令牌 [英] Including csrf token in a post request from react-native app

查看:63
本文介绍了在来自本机应用程序的发布请求中包含csrf令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个react本机应用程序,该应用程序从远程服务器发布并获取数据.在发布中,我需要包含csrf令牌,以避免令牌不匹配错误.这是后端laravel方法

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'
            ]);
    }

这是React本机代码(我去除了错误捕获代码).

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;
      }

  }

响应显示laravel的令牌不匹配页面.如何成功发送csrf令牌?

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

推荐答案

按照主Laravel布局文件中的定义,将CSRF令牌挂在 window 之外:

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

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

然后只在您的javascript请求中使用它:

Then just use that in your javascript requests:

...window.Laravel.csrfToken

修改

致敬礼的人:这确实是Laravel开箱即用的方式,并建议您也这样做.

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

这篇关于在来自本机应用程序的发布请求中包含csrf令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆